[LeetCode] 110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / 
  9  20
    /  
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / 
     2   2
    / 
   3   3
  / 
 4   4

Return false.

题目要求判断给定的二叉树是不是平衡二叉树。平衡二叉树要求每个结点的左右子树层数相差不超过1层。

因为每个结点的都要符合平衡二叉树的要求,因此使用递归的方法进行求解。

方法一:可以计算每个结点的左右子树的层数来判断是否为平衡二叉树。

代码:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root || (!root->left && !root->right))return true;
        
        if(abs(layer(root->left)-layer(root->right))>1)return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
    int layer(TreeNode* root){
        if(!root)return 0;
        return max(1+layer(root->left),1+layer(root->right));
    }
};

方法二:当子树为非平衡二叉树时就可以不再进行层数的计算和比较了,直接得出二叉树不平衡的结果。

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(layer(root)==-1)return false;
        else return true;
    }
    int layer(TreeNode* root){
        if(!root)return 0;
        int left,right;
        left=layer(root->left);
        right=layer(root->right);
        if(left==-1 || right==-1)return -1;
        if(abs(left-right)>1)return -1;
        return 1+max(left,right);
    }
};

这里需要注意,不要过多的重复递归,否则当二叉树较大时容易导致运行时间过长。

原文地址:https://www.cnblogs.com/cff2121/p/10974514.html