Binary Tree Coloring Game — LeetCode 1145 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#1145
Reading time
4 min

The problem

Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree.

Example

Input
root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output
true
Explanation
The second player can choose the node with value 2.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:
        def dfs(root):
            if root is None or root.val == x:
                return root
            return dfs(root.left) or dfs(root.right)

        def count(root):
            if root is None:
                return 0
            return 1 + count(root.left) + count(root.right)

        node = dfs(root)
        l, r = count(node.left), count(node.right)
        return max(l, r, n - l - r - 1) > n // 2

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1145. Binary Tree Coloring Game is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1145. Binary Tree Coloring Game?
LeetCode 1145. Binary Tree Coloring Game is rated Medium on LeetCode.
What is the time complexity of LeetCode 1145. Binary Tree Coloring Game?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1145. Binary Tree Coloring Game?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1145. Binary Tree Coloring Game cover?
LeetCode 1145. Binary Tree Coloring Game is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview