Day17 | 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和

110.平衡二叉树

当左子树右子树高度差超过一时,即可判断该树不是平衡二叉树,用后序遍历将左右子树的高度返回给根结点,再由上层结点判断其左右子树高度差

class Solution {
public:
    int getDepth(TreeNode*node){
        if(node== nullptr)return 0;
        int left= getDepth(node->left);//左
        if(left==-1)return -1;
        int right= getDepth(node->right);//右
        if(right==-1)return -1;
        int res;
        if(abs(left-right)>1) res=-1;
        else
            res=1+ max(left,right);//中
        return res;
    }
    bool isBalanced(TreeNode* root) {
        int depth=getDepth(root);
        if(depth==-1)return 0;
        return 1;
    }
};

257.二叉树的所有路径

在找到叶子后终止递归,回溯,并把找到的路径存到结果集中,遍历顺序为先序遍历,一刷仍不熟悉回溯,需要掌握中左右遍历顺序内部的代码实现

class Solution {
private:
    void travel(TreeNode*node,vector<int> &path,vector<string> &res){
        //中
        path.push_back(node->val);
        if(node->left== nullptr&&node->right== nullptr){
            string sPath;
            for (int i = 0; i < path.size() - 1; i++) {
                // 将path里记录的路径转为string格式
                sPath += to_string(path[i]);
                sPath += "->";
            }
            sPath += to_string(path[path.size() - 1]); // 记录最后一个节点(叶子节点)
            res.push_back(sPath); // 收集一个路径
            return;
        }
        if(node->left){
            travel(node->left,path,res);
            path.pop_back();//回溯把最后一个结点弹出
        }
        if(node->right){
            travel(node->right,path,res);
            path.pop_back();
        }
    }
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> res;
        if(root== nullptr)return res;
        travel(root,path,res);
        return res;
    }
};

404.左叶子之和

要找到左叶子,即要找到为上层结点左孩子的叶子结点,用后序遍历的原因是把左右孩子的情况都返回给根结点,这样才能得到最后的和

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root== nullptr)return 0;
        if(root->left== nullptr&&root->right== nullptr)return 0;
        //后序
        int leftValue= sumOfLeftLeaves(root->left);//左
        if(root->left&&!root->left->left&&!root->left->right){
            leftValue=root->left->val;
        }
        int rightValue= sumOfLeftLeaves(root->right);//右
        int sum=leftValue+rightValue;//中
        return sum;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值