Binary Tree Coloring Game - 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. n is odd, and each node has a distinct value from 1 to n.

Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.

Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color and colors an uncolored neighbor (either the left child, right child, or parent). If a player cannot choose such a node, they must pass their turn. If both players pass, the game ends, and the winner is the player that colored more nodes.

You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.

Input & Output

Example 1 — Blocking Strategy Works
$ Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
💡 Note: First player chooses node 3. Second player can choose node 1 to block access to the parent subtree, securing more territory.
Example 2 — No Winning Strategy
$ Input: root = [1,2,3], n = 3, x = 2
Output: false
💡 Note: With only 3 nodes total, first player at node 2 can spread to both children. No position gives second player majority.
Example 3 — Perfect Balance
$ Input: root = [1,2,3,4,5], n = 5, x = 1
Output: true
💡 Note: First player at root (node 1) creates two subtrees of size 2 each. Second player can block one subtree and win 3-2.

Constraints

  • 1 ≤ n ≤ 500
  • n is odd
  • 1 ≤ x ≤ n
  • Tree has exactly n nodes with values 1 to n

Visualization

Tap to expand
Binary Tree Coloring Game1First Player (Red)23456Second PlayerPlayers take turns expanding to adjacent nodesGoal: Color more than half the nodes to win
Understanding the Visualization
1
Setup
First player chooses node x, second player chooses node y
2
Expansion
Players alternate turns expanding to adjacent uncolored nodes
3
Victory
Second player wins if they can secure more than half the nodes
Key Takeaway
🎯 Key Insight: Block your opponent's access to their largest potential territory by strategic positioning
Asked in
Google 12 Facebook 8 Amazon 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen