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.



/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int tag =1;
    public boolean isBalanced(TreeNode root) {
        int left,right;
        if(root==null){
            return true;
        }else {
            left = height(root.left);
            right =height(root.right);
           // if(left <0 || right<0){
            if(tag ==-1){
                return false;
            }else{
                if(Math.abs(left-right)>1){
                    return false;
                }else{
                    return true;
                }
            }
              
          }
    }
    
    public int height(TreeNode root){
        int left,right;
        if(root==null){
            return 0;
        }else{
            //对root的左孩子和右孩子分别进行递归计算高度,如果两个孩子的高度相差大于1,则返回-1,表示不平衡
            left = height(root.left);
            right = height(root.right);
            if(Math.abs(left-right)<2){
                return Math.max(left,right)+1;
            }else{
                tag= -1;
                return -1;
            }
            
        }
    }
}

你可能感兴趣的:(LeetCode 110. Balanced Binary Tree)