代码随想录 - 训练营8期- day 17

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

110. 平衡二叉树

AVL 它来了.... 感觉数据结构对他的印象都停留在理论,code早忘了

思路是求左右子树高度差肯定没问题

可以用 -1 代表不是平衡二叉树

需要返回的是左右子树的高度最大值(处理 中间结点),所以就有了 res 相关的代码

class Solution {
    int subTreeHeight(TreeNode* root) {
        if(root == nullptr) return 0;
        int left = subTreeHeight(root->left);
        if(left < 0) return -1;
        int right = subTreeHeight(root->right);
        if(right < 0) return -1;
        
        int res = 0;
        if(abs(left - right) > 1) {
            res = -1;
        } else {
            res = 1 + max(left, right);
        }

        return res;
    }
public:
    bool isBalanced(TreeNode* root) {
        int h = subTreeHeight(root);
        return h < 0 ? false : true;
    }
};

257. 二叉树所有路径

这个题一眼回溯...

回溯都懂,差不多套路

回溯的话都是递归完成纵向遍历,循环完成横向遍历,那二叉树简单,每层固定2次,if判断一下就行

但是代码我已经忘却了,直接看了随想录

顺便记录一下 std::to_string()

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

404. 左叶子之和

想清楚边界就行了。

class Solution {
    int getLeftSum(TreeNode* root) {
        if(root == nullptr) return 0;
        int lval = getLeftSum(root->left);
        if(root->left != nullptr && root->left->left == nullptr && root->left->right == nullptr) {
            lval = root->left->val;
        }
        int rval = getLeftSum(root->right);
        return lval + rval;
    }
public:
    int sumOfLeftLeaves(TreeNode* root) {
        return getLeftSum(root);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值