Skip to main content
Back to problems
#1145
Medium Algorithms

Binary tree coloring game

Tree Depth-First Search Binary Tree
52.9% acceptance
Feb 27, 2026
1402
225
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 (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, 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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
  pub fn btree_game_winning_move(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, n: i32, x: i32) -> bool {
    let mut left_size = 0i32;
    let mut right_size = 0i32;
    Self::count(&root, x, &mut left_size, &mut right_size);
    let parent_size = n - 1 - left_size - right_size;
    let half = n / 2;
    left_size > half || right_size > half || parent_size > half
  }

  fn count(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, x: i32,
       left: &mut i32, right: &mut i32) -> i32 {
    match node {
      None => 0,
      Some(n) => {
        let val = n.borrow().val;
        let l = n.borrow().left.clone();
        let r = n.borrow().right.clone();
        let lc = Self::count(&l, x, left, right);
        let rc = Self::count(&r, x, left, right);
        if val == x {
          *left  = lc;
          *right = rc;
        }
        1 + lc + rc
      }
    }
  }
}