判断给定的二叉树是否是平衡的
在这个问题中,定义平衡二叉树为每个节点的左右两个子树高度差的绝对值不超过1的二叉树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return bool布尔型
*/
public boolean isBalanced (TreeNode root) {
if(root==null) return true;
return getheight(root)!=-1;
}
public int getheight(TreeNode root){
if(root==null) return 0;
//判断左子树长度
int left= getheight(root.left);
if(left==-1) return -1;
//判断右子树长度
int right= getheight(root.right);
if(right==-1) return -1;
if(right-left>1 ||left-right>1) return -1;
return 1+ Math.max(left,right);
}
}