题目 解题 首先利用递归计算左右子树高度,其中叶子阶段为空(base case)所以返回0;计算高度int leftHeight=getHeight(root.left); int rightHeght=getHeight(root.right);返回左右子树最大的高度然后比较左右子树最大高度,发现根节点平衡了,左右数不一定平衡,所以继续递归,查看子树是否平衡。理解递归,不要套在里边,要直接分析最简单的情况怎么实现,在宏观的查看规律。还有一定要设置出口条件,不然死循环出错。这种解决方法复杂度比较大,因为他相当于遍历了两次,还有第二种方法,自行度娘。 public boolean isBalanced (TreeNode root) { // write code here if(root ==null)return true;//base case int leftHeight=getHeight(root.left); int rightHeight=getHeight(root.right); if(Math.abs(rightHeight-leftHeight)>1)return false; return isBalanced(root.left)&&isBalanced(root.right);//保证左右子树也为平衡 } private int getHeight(TreeNode root){ if(root == null)return 0;//bese cose int leftHeight=getHeight(root.left); int rightHeight=getHeight(root.right); return Math.max(leftHeight,rightHeight)+1; }