边界样例有点多
/*
* @lc app=leetcode id=1145 lang=cpp
*
* [1145] Binary Tree Coloring Game
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int dfsSum(TreeNode* now){
if(now == NULL) return 0;
int num = 0;
num += dfsSum(now->left);
num += dfsSum(now->right);
return num + 1;
}
bool dfs(TreeNode* now, int val, int all) {
if(now->val == val) {
int xRoot = dfsSum(now);
int xLeft = dfsSum(now->left);
int xRight = dfsSum(now->right);
if(xRoot <= all/2 || xLeft > all - xRoot + xRight + 1 || xRight > all - xRoot + xLeft + 1) {
return true;
}
return false;
}
bool ans = false ;
if(now->left != NULL){
ans = ans || dfs(now->left, val, all);
}
if(now->right != NULL){
ans = ans || dfs(now->right, val, all);
}
return ans;
}
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
return dfs(root, x, n);
}
};
// @lc code=end