LeetCode日常刷题110

110. 平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false

二叉平衡树定义为:binary tree in which the depth of the two subtrees of every node never differ by more than 1.

即任意一个节点的两个子树深度差不超过1.

先写一个函数递归得到任意一个节点的深度,

判断是否为平衡树的条件为:

1.根节点为空,是

2.根节点不为空,左右两子树的深度差1以上,不是

3.左右两子树的深度差1以内,如果两个子树都是平衡树,则是,否则不是

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static auto x = [](){
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root == NULL)return true;
        int h = 0;
        return helper(root, h);
    }
private:
    bool helper(TreeNode* root, int& h){
        int l = 0, r = 0;
        if(root->left)
            if(!helper(root->left, l))return false;
        if(root->right)
            if(!helper(root->right, r))return false;
        if(l - r > 1 || r - l > 1)return false;
        h = max(l, r) + 1;
        return true;
    }
};
/**
 * 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 {  
    private:    
        int depth(TreeNode* root) {  
            if (root == NULL) {  
                return 0;  
            } else {  
               int left_depth = depth(root->left);  
               int right_depth = depth(root->right);  
               if (left_depth == -1 || right_depth == -1 || (left_depth - right_depth > 1) || (left_depth - right_depth < -1))   
                    return -1;  
               else if (left_depth - right_depth > 0)   
                    return left_depth + 1;  
               else return right_depth + 1;  
            }  
        }  
    public:  
      
        bool isBalanced(TreeNode *root) {  
            if (root == NULL) return true;  
            else return (depth(root) !=-1);  
        }  
    };  

猜你喜欢

转载自blog.csdn.net/zhang_yixuan_ss/article/details/80258306
今日推荐