forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-coloring-game.cpp
36 lines (34 loc) · 961 Bytes
/
binary-tree-coloring-game.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
pair<int, int> left_right;
count(root, x, &left_right);
const auto& [left, right] = left_right;
const auto blue = max(max(left, right),
n - (left + right + 1));
return blue > n - blue;
}
private:
int count(TreeNode *root, int x, pair<int, int> *left_right) {
if (!root) {
return 0;
}
const auto& left = count(root->left, x, left_right);
const auto& right = count(root->right, x, left_right);
if (root->val == x) {
*left_right = make_pair(left, right);
}
return left + right + 1;
}
};