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:**

Input:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3Output:trueExplanation: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: Count size of red’s subtrees**

There are two situations that blue can win.

1. one of the red’s subtree has more than n>>1 nodes. Blue colorize the root of the larger subtree.

2. red and its children has size less or equal to n>>1. Blue colorize red’s parent.

Time complexity: O(n)

Space complexity: O(h)

## C++

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua class Solution { public: bool btreeGameWinningMove(TreeNode* root, int n, int x) { int red_left; int red_right; function<int(TreeNode*)> count = [&](TreeNode* node){ if (!node) return 0; int l = count(node->left); int r = count(node->right); if (root->val == x) { red_left = l; red_right = r; } return 1 + l + r; }; count(root); // Color red's parent. if (1 + red_left + red_right <= n / 2) return true; // Color the child that has the larger subtree. return max(red_left, red_right) > n / 2; } }; |

请尊重作者的劳动成果，转载请注明出处！花花保留对文章／视频的所有权利。

如果您喜欢这篇文章／视频，欢迎您捐赠花花。

If you like my articles / videos, donations are welcome.

## Be First to Comment