题目描述
在这里插入图片描述
思路
一号玩家选择节点后,将树分成了三个部分:左子树,右子树和其父节点另外一个子树。
- 如果左子树节点数目(left)大于总节点数目的一半,返回true
- 如果右子树节点数目(right)大于总节点数目的一半,返回false
- 如果left+right 小于总节点数目的一半(其父节点另外一个子树节点数目大于总节点数目的一半),返回true
/**
* 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:
bool btreeGameWinningMove(TreeNode* root, int n, int x) {
TreeNode* xRoot= findxRoot(root, x);
int left = countNodes(xRoot->left);
int right = countNodes(xRoot->right);
int half = n / 2;
if (left > half || right > half || left+right < half){
return true;
}
return false;
}
private:
int countNodes(TreeNode* root){
if (root == NULL){
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
TreeNode* findxRoot(TreeNode* root, int x){
if (root == NULL) {
return NULL;
}
if (root->val == x){
return root;
}
TreeNode* left = findxRoot(root->left, x);
TreeNode* right = findxRoot(root->right, x);
return left == NULL ? right : left;
}
};```