代码随想录算法训练营第十七天|二叉树

110. 平衡二叉树

class Solution {
public:
    int height(TreeNode* root) {
        if (root == nullptr) return 0;
        int heightLeft = height(root->left);
        int heightRight = height(root->right);
        if (heightLeft == -1 || heightRight == -1 || abs(heightLeft - heightRight) > 1) {
            return -1;
        }
        return max(heightLeft, heightRight) + 1;
    }
    bool isBalanced(TreeNode* root) {
        return height(root) >= 0;
    }
};

257. 二叉树的所有路径

class Solution {
public:
    vector<string> result;
    void dfs(TreeNode* root, string path) {
        if (root == nullptr) return;
        if (root->left == nullptr && root->right == nullptr) {
            result.push_back(path + to_string(root->val));
        }
        if (root->left) {
            dfs(root->left, path + to_string(root->val) + "->");
        }
        if (root->right) {
            dfs(root->right, path + to_string(root->val) + "->");
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        dfs(root, path);
        return result;
    }
};

404. 左叶子之和

class Solution {
public:
    int sumLeft(TreeNode* root, bool leftLeaves) {
        if (root == nullptr) return 0;
        if (root->left == nullptr && root->right == nullptr && leftLeaves) {
            return root->val;
        }
        if (root->left && root->right) {
            return sumLeft(root->left, true) + sumLeft(root->right, false);
        }
        else if (root->left) {
            return sumLeft(root->left, true);
        }
        else {
            return sumLeft(root->right, false);
        }
    }
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == nullptr) return 0;
        return sumLeft(root, false);
    }
};

一切尽在不言中,自己的代码量需要不断积累,欲速则不达

这个学期的学系会很累,会很忙,但是无论如何记住,不要给自己所谓的计划,尽量少玩一点,能用来学习的时间就用来学习,尽力而为即可,不要去想结果能够怎么样,但是对自己也有要求,目标这学期每门课都能拿到3.7,不要像之前那样抱着什么都无所谓的态度了,认真看待每门课与考试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值