【代码随想录第17天】二叉树4

110. 平衡二叉树(简单)

题目链接:110. 平衡二叉树
代码随想录:110. 平衡二叉树

递归比较左右子树的高度差

class Solution {
public:
    int getHeight(TreeNode *root){
        if(!root) return 0;
        int leftH = getHeight(root->left);
        if(leftH == -1) return -1;
        int rightH = getHeight(root->right);
        if(rightH == -1) return -1;
        return abs(leftH - rightH) > 1 ? -1 : 1 + max(leftH, rightH);
    } 
    bool isBalanced(TreeNode* root) {
        return getHeight(root) == -1 ? false : true;
    }
};

257. 二叉树的所有路径(简单)

LeetCode题目:257. 二叉树的所有路径
代码随想录:257. 二叉树的所有路径

回溯
到叶子节点时收集结果。

class Solution {
public:
    vector<string> res;
    vector<int> path;
    void backtracking(TreeNode* root){
        path.push_back(root->val);
        if(!root->left && !root->right){
            string s;
            int i = 0;
            for(; i < path.size() - 1; i++){
                s += to_string(path[i]);
                s += "->";
            }
            s += to_string(path[i]);
            res.push_back(s);
            return;
        }       
        if(root->left) {
            backtracking(root->left);
            path.pop_back();
        }
        if(root->right) {
            backtracking(root->right);
            path.pop_back();
        }
        
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root) return res;
        backtracking(root);
        return res;
    }
};

404.左叶子之和 (简单)

LeetCode题目:404.左叶子之和
代码随想录:404.左叶子之和


第一想法:左叶子:root->left && !root->left->left && !root->left->right
sum可以设置为全局变量

class Solution {
public:
    int sum = 0;
    int sumOfLeftLeaves(TreeNode* root) {
        if(root->left && !root->left->left && !root->left->right)
            sum += root->left->val;
        if(root->left) sumOfLeftLeaves(root->left);
        if(root->right) sumOfLeftLeaves(root->right);
        return sum;
    }
};

文章中解法

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL) return 0;
        if(!root->left && !root->right) return 0;
        int leftVal = sumOfLeftLeaves(root->left);
        // 判断是否为左叶子节点需要通过父节点
        if(root->left && !root->left->left && !root->left->right)
            leftVal = root->left->val;
        int rightVal = sumOfLeftLeaves(root->right);
        return leftVal + rightVal;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值