Skip to content

Commit 0592964

Browse files
authored
Create binary-tree-coloring-game.cpp
1 parent cbcc15a commit 0592964

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

C++/binary-tree-coloring-game.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
16+
pair<int, int> left_right;
17+
count(root, x, &left_right);
18+
const auto& [left, right] = left_right;
19+
const auto blue = max(max(left, right),
20+
n - (left + right + 1));
21+
return blue > n - blue;
22+
}
23+
24+
private:
25+
int count(TreeNode *root, int x, pair<int, int> *left_right) {
26+
if (!root) {
27+
return 0;
28+
}
29+
const auto& left = count(root->left, x, left_right);
30+
const auto& right = count(root->right, x, left_right);
31+
if (root->val == x) {
32+
left_right->first = left;
33+
left_right->second = right;
34+
}
35+
return left + right + 1;
36+
}
37+
};

0 commit comments

Comments
 (0)