【第十七天】二叉树还需复习!

文章介绍了三个关于二叉树的问题解决方案:1)BalancedBinaryTree关注于判断一棵二叉树是否平衡,使用递归计算左右子树的深度;2)BinaryTreePaths解决找到二叉树的所有路径,通过递归生成路径字符串;3)SumofLeftLeaves计算所有左叶子节点的值之和,同样采用递归方法。每个问题都强调了对二叉树特性和递归的理解与应用。
  1. Balanced Binary Tree

第二遍了,还是没写出来。受挫了。
本题要点:
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;
    }
};

2.Binary Tree Paths

昨天被这道题搞得心态爆炸了:做过一遍的题为什么还是不会?今天心态摆正了,只看一眼就改过来错误了。
思路:什么时候是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;
    }
};

3.Sum of Left Leaves

依照上题思路,如果碰到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;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值