输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null||(root.left==null&&root.right==null)){
return true;
}
int left = treeDepth(root.left);
int right = treeDepth(root.right);
return Math.abs(left-right)<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
public int treeDepth(TreeNode root){
if(root!=null){
return Math.max((treeDepth(root.left)+1),(treeDepth(root.right)+1));
}
return 0;
}
}