【发布时间】:2015-05-25 09:04:06
【问题描述】:
我正在解决“Cracking the Coding Interview”中的以下问题:实现一个函数来检查二叉树是否平衡。平衡树是一棵树,使得任何节点的两个子树的高度都不会相差超过 1。
本书的示例解决方案(复制如下)假设从节点发出的树是平衡的,如果 (a) 节点的左子树和右子树是平衡的; (b) 节点本身是平衡的。我试图理解为什么会这样?上述两个条件的满足如何证明从节点发出的整棵树是平衡的?
谢谢
public static boolean isBalanced(TreeNode root)
{
if (checkHeight(root)==-1)
return false;
return true;
}
public static int checkHeight(TreeNode root)
{
//base case
if (root == null)
return 0;
//is left subtree balanced
int leftHeight = checkHeight(root.leftChild);
if (leftHeight == -1)
return -1;
//is right subtree balanced
int rightHeight = checkHeight(root.rightChild);
if (rightHeight == -1)
return -1;
//is current node balanced
int heightDiff = leftHeight - rightHeight;
if (Math.abs(heightDiff) > 1)
return -1;
return (Math.max(leftHeight, rightHeight) + 1);
}
【问题讨论】:
-
为什么没人说Induction?
-
@kutschkem 您能否解释一下,或者指出一个用于证明平衡性的归纳示例?谢谢!
标签: java tree binary-tree tree-balancing