给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
我TM都不知道我是怎么写出来的,递归太难想了
先记录一下,日后再看。
/**
* 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) {
return dosome(root,1) != -1;
}
public int dosome(TreeNode root,int i){
if(root == null) return i-1;
int a = dosome(root.left,i+1);
if(a == -1) return -1;
int b = dosome(root.right,i+1);
if(b == -1) return -1;
if(Math.abs(a-b)>1){
return -1;
}
return Math.max(a,b);
}
}