递归。如果当前节点为null,也说明是平衡树,返回true。如果左子树和右子树的高度差大于1,说明以当前节点作为根节点的树不是平衡树,则直接返回false;如果左子树和右子树的高度差小于等于1,说明以当前节点作为根节点的树是平衡树,则递归判断对其左子树和右子树是否是平衡树。计算树的高度可参考上一题的解答。
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) return true;
if (Math.abs(TreeDepth(root.left) - TreeDepth(root.right)) > 1) {
return false;
} else {
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
}
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
京公网安备 11010502036488号