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);
}