思路:
①先写一个求二叉树深度的递归程序。
②再写判断平衡二叉树的问题,只有当左子树、右子树、当前节点都是平衡的才返回true。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
int leftdep = maxDepth(root.left);
int rightdep = maxDepth(root.right);
boolean curbool = leftdep > rightdep ? leftdep - rightdep <= 1 : rightdep - leftdep <= 1;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right) && curbool;
}
public int maxDepth (TreeNode root) {
// write code here
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}