Problem 1145

Abstract / Summary

Two players color tree nodes alternately starting from a root; the first to color all nodes in a connected part wins.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
39 lines | 1096 bytes | submitted June 28, 2024 | GitHub   57% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (100k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.12 | σ = 1.34

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 13 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

4 solutions   June 28, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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