代码随想录D17

110.平衡二叉树 (优先掌握递归)

题目链接/文章讲解/视频讲解:代码随想录

class Solution {
public:
    struct Info{
        bool isB;
        int height;

        Info(bool isB, int height):isB(isB),height(height){}
    };

    bool isBalanced(TreeNode* root) {
        return traversal(root).isB;
    }

    Info traversal(TreeNode* cur){
        if(cur == nullptr){
            return Info(true, 0);
        }

        Info linfo = traversal(cur->left);
        Info rinfo = traversal(cur->right);

        if(!linfo.isB || !rinfo.isB){
            return Info(false, max(linfo.height,rinfo.height) + 1);
        }
        else{
            if(abs(linfo.height - rinfo.height) < 2){
                return Info(true, max(linfo.height,rinfo.height) + 1);
            }
            else{
                return Info(false, max(linfo.height,rinfo.height) + 1);
            }
        }
    }
};

 257. 二叉树的所有路径 (优先掌握递归)  

题目链接/文章讲解/视频讲解:代码随想录

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        constructPaths(root,"",result);
        return result;
    }

    void constructPaths(TreeNode* cur, string path, vector<string>& result){
        if(cur != nullptr){
            path += to_string(cur->val);
            if(cur->left == nullptr && cur->right == nullptr){
                result.push_back(path);
                return;
            }
            else{
                path+= "->";
                constructPaths(cur->left, path, result);
                constructPaths(cur->right, path, result);
            }
        }
    }
};

 

 404.左叶子之和 (优先掌握递归)

题目链接/文章讲解/视频讲解:代码随想录

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        return sumTotal(root,false);
    }

    int sumTotal(TreeNode* cur, bool isLeft){
        if(cur == nullptr) return 0;
        if(cur->left == nullptr && cur->right == nullptr){
            return isLeft ? cur->val : 0;
        }

        int leftSum = sumTotal(cur->left, true);
        int RightSum = sumTotal(cur->right, false);
        return leftSum + RightSum;
    }
};

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值