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

110.平衡二叉树

题目:110. 平衡二叉树

class Solution {
public:
    int height(TreeNode* root){
        if(root == nullptr) return 0;
        int left_h = height(root->left);
        int right_h = height(root->right);
        return max(left_h,right_h) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(root == nullptr) return true;
        if(abs(height(root->left) - height(root->right) ) > 1) return false;
        return isBalanced(root->left) && isBalanced(root->right);
        
    }
};

257.二叉树的所有路径

题目:257. 二叉树的所有路径

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

404.左叶子之和

题目:404. 左叶子之和

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

    }
};

总结

题型:二叉树的迭代,涉及到回溯

技巧:迭代和回溯结合,确定好题目的定义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值