边界样例有点多
/*
* @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
本文探讨了在LeetCode问题1145中,如何有效地处理边界样例,深入解析了二叉树着色游戏的DFS算法,并提供了解决边界情况的优化策略。通过递归函数dfsSum和dfs,分析了赢得游戏的关键节点条件。

13万+

被折叠的 条评论
为什么被折叠?



