I'm solving the following problem from "Cracking the Coding Interview": Implement a function to check if a binary tree is balanced. A balanced tree is a tree such that the heights of the two subtrees of any node never differ by more than one.
The book's sample solution (copied below) assumes the tree emanating from a node is balanced if (a) the node's left and right subtrees are balanced; and (b) the node itself is balanced. I'm trying to understand why this is the case? How does the fulfillment of the above two conditions prove that the entire tree emanating from the node is balanced?
Thanks
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);
}
Since you asked for it, here some more on induction:
https://en.wikipedia.org/wiki/Well-founded_relation
Forget everything you know about induction, here is the real thing. If we have some relation R, R is said to be well-founded if and only if there is no infinitely descending chain x1, x2, x3, ... with x1 R x2, x2 R x3 and so on. ("descending" because people are thinking of < on numbers )
For example, < is well-founded on the natural numbers, but not on real numbers.
With well-founded relations, you have that
(for all x : (for all y : x R y -> P(y)) -> P(x)) <-> for all x : P(x)
In other words, it is enough to show that all minimal elements wrt. R have some property, and then show that if all smaller elements than some x fulfill P, so does x.
Special case is the induction you probably know:
(P(0) & for all n: P(n) -> P(n+1)) -> for all n: P(n) (the well-founded relation here is the successor function)
For finite trees, the subtree relation is (obviously) well-founded, so we can do (actually let's use the transitive closure, makes the proof shorter. It is still well-founded):
Base case: (leafs, these are mininal wrt subtree relation) leafs with 0 children are balanced, trivially
Induction: Assuming all subtrees (and their subtrees and so on) are balanced, and the root node is balanced, all nodes are balanced, no node is left that could be unbalanced (see what I did here?)
We could have done this without using the transitive closure if we also note that to be balanced implies that the subtrees are balanced. Then we can just say that having the direct subtrees balanced implies that all their subtrees are balanced as well, and we are back at my proof.