|
| 1 | +/** |
| 2 | + * 1145. Binary Tree Coloring Game |
| 3 | + * https://leetcode.com/problems/binary-tree-coloring-game/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Two players play a turn based game on a binary tree. We are given the root of this binary tree, |
| 7 | + * and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. |
| 8 | + * |
| 9 | + * Initially, the first player names a value x with 1 <= x <= n, and the second player names a value |
| 10 | + * y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second |
| 11 | + * player colors the node with value y blue. |
| 12 | + * |
| 13 | + * Then, the players take turns starting with the first player. In each turn, that player chooses |
| 14 | + * a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of |
| 15 | + * the chosen node (either the left child, right child, or parent of the chosen node.) |
| 16 | + * |
| 17 | + * If (and only if) a player cannot choose such a node in this way, they must pass their turn. If |
| 18 | + * both players pass their turn, the game ends, and the winner is the player that colored more |
| 19 | + * nodes. |
| 20 | + * |
| 21 | + * You are the second player. If it is possible to choose such a y to ensure you win the game, |
| 22 | + * return true. If it is not possible, return false. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * Definition for a binary tree node. |
| 27 | + * function TreeNode(val, left, right) { |
| 28 | + * this.val = (val===undefined ? 0 : val) |
| 29 | + * this.left = (left===undefined ? null : left) |
| 30 | + * this.right = (right===undefined ? null : right) |
| 31 | + * } |
| 32 | + */ |
| 33 | +/** |
| 34 | + * @param {TreeNode} root |
| 35 | + * @param {number} n |
| 36 | + * @param {number} x |
| 37 | + * @return {boolean} |
| 38 | + */ |
| 39 | +var btreeGameWinningMove = function(root, n, x) { |
| 40 | + let leftCount = 0; |
| 41 | + let rightCount = 0; |
| 42 | + |
| 43 | + countNodes(root); |
| 44 | + |
| 45 | + const parentCount = n - leftCount - rightCount - 1; |
| 46 | + const maxRegion = Math.max(parentCount, leftCount, rightCount); |
| 47 | + |
| 48 | + return maxRegion > n / 2; |
| 49 | + |
| 50 | + function countNodes(node) { |
| 51 | + if (!node) return 0; |
| 52 | + const left = countNodes(node.left); |
| 53 | + const right = countNodes(node.right); |
| 54 | + if (node.val === x) { |
| 55 | + leftCount = left; |
| 56 | + rightCount = right; |
| 57 | + } |
| 58 | + return left + right + 1; |
| 59 | + } |
| 60 | +}; |
0 commit comments