代码随想录day17

 110.平衡二叉树 (优先掌握递归)

左右子树高度差小于1为平衡二叉树,但每个节点都需要满足这个条件。

class Solution {
public:
    int height(TreeNode* root) {
        if (root == NULL) {
            return 0;
        } else {
            return max(height(root->left), height(root->right)) + 1;
        }
    }

    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        } else {
            return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
        }
    }
};

 257. 二叉树的所有路径 (优先掌握递归)  

这个要回溯

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

 404.左叶子之和 (优先掌握递归)

左叶子的判断方式是:

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值