第二遍了,还是没写出来。受挫了。
本题要点:
res = 1 + max(lDepth, rDepth); 是求深度的办法。这题和二叉树的(深度/高度)深度有关,所以基础的布局就是:
int lDepth = check(root->left); 和 int rDepth = check(root->right);
以及查深度的那一句。
class Solution {
private:
int check(TreeNode* root){
if(!root) return 0;
int lDepth = check(root->left);
if(lDepth == -1) return -1;
int rDepth = check(root->right);
if(rDepth == -1) return -1;
int res;
if(abs(lDepth - rDepth) > 1){
res = -1;
}else{
res = 1 + max(lDepth, rDepth);
}
return res;
}
public:
bool isBalanced(TreeNode* root) {
return check(root) == -1? false: true;
}
};
昨天被这道题搞得心态爆炸了:做过一遍的题为什么还是不会?今天心态摆正了,只看一眼就改过来错误了。
思路:什么时候是leaf node?当!root->left && !root->right的时候。提前预判,把value加进去就好。
class Solution {
private:
vector<string> res;
string tmp = "";
void generatePath(TreeNode* root){
if(!root) return;
if(!root->left && !root->right){
res.push_back(tmp + to_string(root->val));
}
string str = to_string(root->val) + "->";
tmp = tmp + str;
generatePath(root->left);
generatePath(root->right);
tmp = tmp.substr(0, tmp.length()-str.length());
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
generatePath(root);
return res;
}
};
依照上题思路,如果碰到leaf node就判断一下是不是left node。但如果不是,遇到了null,直接return。这样不会漏掉任何一个node,因为第二个if判断的是下一个node而不是这个node。
class Solution {
private:
int sum = 0;
void track(TreeNode* root, bool isLeft){
if(!root) return;
if(!root->left && !root->right && isLeft){
sum += root->val; return;
}
track(root->left, true);
track(root->right, false);
}
public:
int sumOfLeftLeaves(TreeNode* root) {
track(root, false);
return sum;
}
};
文章介绍了三个关于二叉树的问题解决方案:1)BalancedBinaryTree关注于判断一棵二叉树是否平衡,使用递归计算左右子树的深度;2)BinaryTreePaths解决找到二叉树的所有路径,通过递归生成路径字符串;3)SumofLeftLeaves计算所有左叶子节点的值之和,同样采用递归方法。每个问题都强调了对二叉树特性和递归的理解与应用。
900

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



