代码随想录算法训练营第十七天 | 110. 平衡二叉树 257. 二叉树的所有路径 404. 左叶子之和

LeetCode110. 平衡二叉树

题目链接
视频讲解

题解

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        int height = getHeight(root);
        if(height == -1) return false;
        return true;
    }

    int getHeight(TreeNode* cur) {
        if(!cur) return 0;

        int leftheight = getHeight(cur -> left);
        if(leftheight == -1) return -1;

        int rightheight = getHeight(cur -> right);
        if(rightheight == -1) return -1;

        return abs(leftheight - rightheight) > 1 ? -1 : max(leftheight, rightheight) + 1;

    }
};

LeetCode257. 二叉树的所有路径

题目链接
视频讲解

题解

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        vector<int> path;
        if(!root) return res;
        getTreePath(root, res, path);
        return res;
    }

    void getTreePath(TreeNode* cur, vector<string>& res, vector<int>& path) {
        path.push_back(cur -> val);

        if(cur -> left == NULL && cur -> right == NULL) {
            string sPath = "";
            for(int i = 0; i < path.size() - 1; i++) {
                sPath += to_string(path[i]);
                sPath += "->";
            }
            sPath += to_string(path[path.size() - 1]);
            res.push_back(sPath);
        } 

        if(cur -> left) {
            getTreePath(cur -> left, res, path);
            path.pop_back();
        }
        if(cur -> right) {
            getTreePath(cur -> right, res, path);
            path.pop_back();
        }
    }
};

LeetCode404. 左叶子之和

题目链接
视频讲解

题解

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(!root) return 0;

        if(root -> left == NULL && root -> right == NULL) return 0;

        int leftCount = sumOfLeftLeaves(root -> left);

        if(root -> left && !root -> left -> left && !root -> left -> right) {
            leftCount = root -> left -> val;
        }

        int rightCount = sumOfLeftLeaves(root -> right);

        return leftCount + rightCount;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值