Just a question here - wouldnât it make more sense to get the left subtree height, check if the left subtree is balanced, get the right subtree height, and then check if the right subtree is balanced? It seems to me that you potentially save some work if you determine that the left subtree is unbalanced first, then you would never even have to check the right subtree. It does make the recursive function a couple lines longer, but was just curious if that makes sense. So instead of:
nt leftHeight = treeHeight(tree.left);
int rightHeight = treeHeight(tree.right);
if (leftHeight == -1 || rightHeight == -1) {
return -1;
}
if would be:
// Get the left subtree height
int leftHeight = dfs(node.left);
// If leftHeight returns as -1, this is our flag that our left
// subtreee is not balanced
if (leftHeight == -1) {
return leftHeight;
}
// Get the right subtree height
int rightHeight = dfs(node.right);
// If rightHeight returns as -1, this is our flag that our right
// subtreee is not balanced
if (rightHeight == -1) {
return rightHeight;
}
How come Test #2 and Test #5 are supposed to be imbalanced?
Test #2: 1 2 4 x 7 x x 5 x x 3 x 6 8 x x x == >(left:3 , right: 3)
|1|
|2| |3|
|4| |5| |6|
|7| |8|
Test #5: 1 2 3 x x 4 x x 5 6 x 7 x x x (left:2, right: 3)
Hi Shaimaa,
This confused me too. It turns out all subtrees have to be balanced in order for the tree to be balanced. (I think this was unclear in the overview since they only say âboth its subtreeâ, and not all its subtrees.)
As you point out, the left and right subtrees of the root node do have heights within 1 level of each other. However, each has a subtree that is out of balance. For example, in test #2, the subtree 3 x 6 8 x x x is out of balance.
Hope this helps!
public static int height(Node tree) {
if (tree == null) return 0;
// decide on what to return when visiting this node
// we want to return the height of the tree.
// height of the tree is the largest number of edges from the root to that tree
int lhsHeight = height(tree.left) + 1;
int rhsHeight = height(tree.right) + 1;
return Math.max(lhsHeight, rhsHeight);
}
public static boolean isBalanced(Node<Integer> tree) {
// WRITE YOUR BRILLIANT CODE HERE
if (tree == null) {
return true;
}
int lhsHeight = height(tree.left);
int rhsHeight = height(tree.right);
boolean lhsBalanced = isBalanced(tree.left);
boolean rhsBalanced = isBalanced(tree.right);
if (Math.abs(lhsHeight - rhsHeight) <= 1) {
return lhsBalanced && rhsBalanced;
}
return false;
}