Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1145.html

1145. Binary Tree Coloring Game

Level

Medium

Description

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.

Example 1:

Image text

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.

Constraints:

  • root is the root of a binary tree with n nodes and distinct node values from 1 to n.
  • n is odd.
  • 1 <= x <= n <= 100

Solution

Define a method to count the number of nodes in a subtree when given the root of the subtree. This can be done using breadth first search.

Consider two cases.

  1. The root node has value x. Then obtain the two children of the root and count the number of nodes in both subtrees such that the roots are the two children respectively. If a child is null, then the number of nodes in the subtree is 0. If both subtrees have the same number of nodes, then return false since the first player can always color one of the entire subtrees. If the two subtrees have different numbers of nodes, then return true since the second player can always color the root of the subtree with more nodes.

  2. The node with value x is not the root. Find the node, and it has at most three neighbors, which are its left child, its right child and its parent. Count the number of nodes in both subtrees of the node, and count the number of remaining nodes after removing the current subtree (with the current node as the root). After obtaining the numbers of nodes in the three parts, check whether there exists one part that have nodes greater than n / 2. If so, the second player can just color the corresponding neighbor and guarantee to win the game, so return true. Otherwise, the second player can never color more than n / 2 nodes no matter which node is colored by the second player (since the total numbers of nodes in one part is not more than than n / 2), so return false.

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
            int half = n / 2;
            if (root.val == x) {
                TreeNode left = root.left, right = root.right;
                if (left == null || right == null)
                    return true;
                int count = countNodes(left);
                if (count == half)
                    return false;
                else
                    return true;
            } else {
                TreeNode xNode = null;
                Queue<TreeNode> queue = new LinkedList<TreeNode>();
                queue.offer(root);
                while (!queue.isEmpty()) {
                    TreeNode node = queue.poll();
                    if (node.val == x) {
                        xNode = node;
                        break;
                    } else {
                        TreeNode left = node.left, right = node.right;
                        if (left != null)
                            queue.offer(left);
                        if (right != null)
                            queue.offer(right);
                    }
                }
                int leftCount = 0, rightCount = 0;
                TreeNode xLeft = xNode.left, xRight = xNode.right;
                if (xLeft != null)
                    leftCount = countNodes(xLeft);
                if (xRight != null)
                    rightCount = countNodes(xRight);
                int remainCount = n - 1 - leftCount - rightCount;
                if (leftCount > half || rightCount > half || remainCount > half)
                    return true;
                else
                    return false;
            }
        }
    
        public int countNodes(TreeNode root) {
            int count = 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                count++;
                TreeNode left = node.left, right = node.right;
                if (left != null)
                    queue.offer(left);
                if (right != null)
                    queue.offer(right);
            }
            return count;
        }
    }
    
  • // OJ: https://leetcode.com/problems/binary-tree-coloring-game/
    // Time: O(N)
    // Space: O(H)
    class Solution {
        int left = 0, right = 0;
    public:
        bool btreeGameWinningMove(TreeNode* root, int n, int x) {
            function<int(TreeNode*)> dfs = [&](TreeNode *root) {
                if (!root) return 0;
                int L = dfs(root->left), R = dfs(root->right);
                if (root->val == x) left = L, right = R;
                return 1 + L + R;
            };
            int total = dfs(root), mx = max({ left, right, total - 1 - left - right });
            return mx > total - mx;
        }
    };
    
  • # 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
    
    ############
    
    # 1145. Binary Tree Coloring Game
    # https://leetcode.com/problems/binary-tree-coloring-game/
    
    # 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:
        left, right = 0, 0
        def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:
            
            def count(node):
                if not node: return 0
                
                l, r = count(node.left), count(node.right)
                if node.val == x:
                    self.left, self.right = l, r
                
                return l + r + 1
            
            count(root)
            left, right = self.left, self.right
            
            first = left > (n - left)
            second = right > (n - right)
            third = (n - left - right - 1) > (1 + left + right)
            
            return first or second or third
    
    
  • /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func btreeGameWinningMove(root *TreeNode, n int, x int) bool {
    	var dfs func(*TreeNode) *TreeNode
    	dfs = func(root *TreeNode) *TreeNode {
    		if root == nil || root.Val == x {
    			return root
    		}
    		node := dfs(root.Left)
    		if node != nil {
    			return node
    		}
    		return dfs(root.Right)
    	}
    
    	var count func(*TreeNode) int
    	count = func(root *TreeNode) int {
    		if root == nil {
    			return 0
    		}
    		return 1 + count(root.Left) + count(root.Right)
    	}
    
    	node := dfs(root)
    	l, r := count(node.Left), count(node.Right)
    	return max(max(l, r), n-l-r-1) > n/2
    }
    
    func max(a, b int) int {
    	if a > b {
    		return a
    	}
    	return b
    }
    
  • /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     val: number
     *     left: TreeNode | null
     *     right: TreeNode | null
     *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.left = (left===undefined ? null : left)
     *         this.right = (right===undefined ? null : right)
     *     }
     * }
     */
    
    function btreeGameWinningMove(
        root: TreeNode | null,
        n: number,
        x: number,
    ): boolean {
        const dfs = (root: TreeNode | null): TreeNode | null => {
            if (!root || root.val === x) {
                return root;
            }
            return dfs(root.left) || dfs(root.right);
        };
    
        const count = (root: TreeNode | null): number => {
            if (!root) {
                return 0;
            }
            return 1 + count(root.left) + count(root.right);
        };
    
        const node = dfs(root);
        const l = count(node.left);
        const r = count(node.right);
        return Math.max(l, r, n - l - r - 1) > n / 2;
    }
    
    
  • /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @param {number} n
     * @param {number} x
     * @return {boolean}
     */
    var btreeGameWinningMove = function (root, n, x) {
        const dfs = root => {
            if (!root || root.val === x) {
                return root;
            }
            return dfs(root.left) || dfs(root.right);
        };
    
        const count = root => {
            if (!root) {
                return 0;
            }
            return 1 + count(root.left) + count(root.right);
        };
    
        const node = dfs(root);
        const l = count(node.left);
        const r = count(node.right);
        return Math.max(l, r, n - l - r - 1) > n / 2;
    };
    
    

All Problems

All Solutions