Python 1145.py
class Solution:
def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
# idea: player 2 is free to choose his initial node
# in order to cover the most nodes it's optimal to pick the best of these three nodes:
# case A: parent of n
# case B: left children of n
# case C: right children of n
# three cases
a = 0
b = 0 # size of left subtree of n
c = 0 # size of right subtree of n
def deeper(node):
if not node:
return 0
left = deeper(node.left)
right = deeper(node.right)
# A's initial node
if node.val == x:
nonlocal b, c
b = left
c = right
return left + 1 + right
# start counting
deeper(root)
# three cases
total = deeper(root)
a = total - b - c - 1
# no parent
if x == root.val:
parent = 0
return 2 * max(a, b, c) > n
Difficulty
and has an acceptance rate of about 53% (100k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method that decides whether the second player can guarantee a win in a two-player game played on a binary tree. The game revolves around a chosen node x; the second player may start from any node that is not already taken. The algorithm evaluates three strategic regions relative to x: the subtree rooted at the left child of x, the subtree rooted at the right child of x, and the remainder of the tree that lies above x (the “parent” region). By measuring the number of nodes in each region and comparing the largest region to half of the total node count n, the method returns a Boolean indicating if a winning move exists for player 2.
Key Steps
Recursive size computation
A nested helper function deeper walks the tree recursively. For each node it obtains the size of the left and right sub-trees, adds one for the current node, and returns the total. When the recursion reaches the node whose value equals x, it records the sizes of its left and right sub-trees in the non-local variables b and c.
def deeper(node):
if not node:
return 0
left = deeper(node.left)
right = deeper(node.right)
# capture sizes when the target node is found
if node.val == x:
nonlocal b, c
b = left
c = right
return left + 1 + right
First traversal - capture left and right subtree sizes
The first call to deeper(root) populates b and c with the exact counts of nodes that lie in the left and right sub-trees of x. No other side-effects are required at this stage.
deeper(root) # fills b and c
Second traversal - total node count
A second invocation of deeper(root) yields the total number of nodes in the tree, stored in total. This value is used to compute the size of the “parent” region a, which consists of all nodes that are not part of x’s left or right sub-trees and not x itself.
total = deeper(root)
a = total - b - c - 1
Handling the root-as-x edge case
If the chosen node x happens to be the root of the tree, there is no parent region. The code explicitly checks this condition and assigns a size of zero to the parent region, ensuring that subsequent calculations remain correct.
if x == root.val:
parent = 0 # a is already zero in this scenario
Winning condition evaluation
The final decision hinges on whether the largest of the three regions contains more than half of the nodes. Multiplying the maximum region size by two and comparing it to n yields a Boolean result that directly answers the game-theoretic question.
return 2 * max(a, b, c) > n
Edge Cases Addressed
When x is the root node, the parent region does not exist; the code treats this situation by setting the parent size to zero, which naturally reduces the comparison to the two sub-trees of the root.
If either the left or right child of x is missing, the corresponding subtree size (b or c) becomes zero because the recursive helper returns zero for a None child. This correctly reflects that player 2 cannot claim any nodes from a non-existent branch.
The algorithm also works when the tree consists of a single node (n = 1). In that case b, c, and a are all zero, and the final condition evaluates to False, indicating that player 2 cannot win, which aligns with the game rules.
Performance Optimizations
The recursion leverages the call stack to traverse the tree without allocating auxiliary data structures such as explicit stacks or queues. This approach minimizes memory overhead while still visiting each node exactly once per traversal.
Although the method performs two separate traversals-one to capture the left and right subtree sizes and another to compute the total node count-each traversal runs in linear time relative to the number of nodes, and the overall constant factor remains low because the work done per node is limited to a few integer operations and a conditional check.
The use of nonlocal variables b and c allows the helper to communicate the required subtree sizes back to the outer scope without returning a composite data structure, thereby avoiding additional object creation and keeping the runtime footprint minimal.
ELI5 - Simplified Explanation
Imagine a big tree made of wooden blocks. Each block is connected to others below it, like branches spreading out. You and a friend are playing a game where you both want to color as many blocks as possible in your own favorite color.
First, you pick one block to start with. Then, the game calculates how big the group of blocks above your friend's block is, how big the group is to the left, and how big the group is to the right. Those groups are like little families of blocks.
The code looks at those three groups. One group is the part of the tree that stays behind if you cut off the branch where the friend started. The other two groups are the smaller pieces hanging directly off that starting block.
The secret to winning is to find which of those three groups is the biggest. If the biggest group has more than half of all the blocks in the whole tree, then picking the block right next to it is the best move. The code simply counts all the blocks in those groups, compares them to see which one is the largest, and checks if that largest group is big enough to win the game.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | JS | Java | Python | Go | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1292: Maximum Side Length of a Square with Sum Less than or Equal to Threshold
- problem 1536: Minimum Swaps to Arrange a Binary Grid
- problem 1946: Largest Number After Mutating Substring
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality