Check if a binary tree is balanced.
The source code on the CTCI 5th:
public class QuestionBrute {
public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public static boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int heightDiff = getHeight(root.left) - getHeight(root.right);
if (Math.abs(heightDiff) > 1) {
return false;
}
else {
return isBalanced(root.left) && isBalanced(root.right);
}
}
public static void main(String[] args) {
// Create balanced tree
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode root = TreeNode.createMinimalBST(array);
System.out.println("Root? " + root.data);
System.out.println("Is balanced? " + isBalanced(root));
// Could be balanced, actually, but it's very unlikely...
TreeNode unbalanced = new TreeNode(10);
for (int i = 0; i < 10; i++) {
unbalanced.insertInOrder(AssortedMethods.randomIntInRange(0, 100));
}
System.out.println("Root? " + unbalanced.data);
System.out.println("Is balanced? " + isBalanced(unbalanced));
}
}
As the algorithm has to check the height of every node, and we don’t save the height in each recursion, the running time should be O(N^2).
First of all let’s fix a bit your code. Your function to check if the root is balanced will not work simply because a binary tree is balanced if:
I quote Wikipedia: “A balanced binary tree is commonly defined as a binary tree in which the depth of the two subtrees of every node differ by 1 or less”
Your algorithm will give the wrong answer for this tree:
When you call
getHeight(Node7)it will return 3, and when you callgetHeight(Node5)it will return 3 as well and since(0>1) == falseyou will returntrue🙁To fix this all you have to do is to implement the
int MinHeight(TreeNode node)the same way you didgetHeight()but withMath.min()Now to your answer. In terms of runtime complexity whenever you call the
getHeight()function from the root you are doing a DFS and since you have to visit all the nodes to find the height of the tree this algorithm will be O(N). Now it is true you execute this algorithm twice, when you callmaxHeight(root)andminHeight(root)but since they are both O(N) (given that they do exactly whatgetHeight()does) the overall complexity will have C*N as an upper limit for some constant C and all N bigger than some N knot i.e. O(N) where N is the number of nodes of your tree 😉Cheers!