1145. Binary Tree Coloring Game
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.TreeNode* findNode(TreeNode* node, int target) {
if (!node) return nullptr;
TreeNode* res = nullptr;
if (node->val == target) res = node;
else {
res = findNode(node->left, target);
if (!res) res = findNode(node->right, target);
}
return res;
}
void countChildren(TreeNode* node, int& cnt) {
if (!node) return;
++cnt;
countChildren(node->left, cnt);
countChildren(node->right, cnt);
}
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
int left_cnt = 0, right_cnt = 0, parent_cnt = 0, second_cnt = 0;
TreeNode* cur = findNode(root, x);
if (!cur) return false;
countChildren(cur->left, left_cnt);
countChildren(cur->right, right_cnt);
if (cur != root) parent_cnt = n - (left_cnt + right_cnt + 1);
second_cnt = max({left_cnt, right_cnt, parent_cnt});
return second_cnt > (n - second_cnt);
}Last updated
