leetcode每日刷题计划-简单篇day17

嘻嘻嘻提前做了算到新的一天,吃烤肉巨开心呀

Num 110 平衡二叉树

注意是每一层都要平衡才行,刚开始只记得判断root了

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL) return true;
        if(abs(getLevel(root->left)-getLevel(root->right))>1) 
           return false;
        return (isBalanced(root->left) && isBalanced(root->right));
    }
    int getLevel(TreeNode*root)
    {
        if(root==NULL) return 0;
        return max(getLevel(root->left),getLevel(root->right))+1;
    }
};
View Code

 Num 111 二叉树的最小深度

题不难但是仍然没有一次做对,这个求得是最短深度,注意一下,如果左边有点右边没有,这时候不能当成右边是0。比如[1,2]是两层的,在解决树相关的问题的时候注意一下。

第一,要注意是不仅仅判断root,第二,要考虑到对叶子节点和null节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL) return 0;
        if(root->left==NULL && root->right==NULL) return 1;
        if(root->left==NULL) return minDepth(root->right)+1;
        if(root->right==NULL) return minDepth(root->left)+1;
        return min(minDepth(root->left),minDepth(root->right))+1;
    }
};
View Code

猜你喜欢

转载自www.cnblogs.com/tingxilin/p/11141287.html