Again we try D&C first. Assign tasks to leftSubtree and rightSubtree to see if they are both balanced then report to the root. If either left or right is not balanced, then the whole tree is not balanced. Or the height difference is greater than 1 then also not balanced.
Code
Very similar to maxDepth problem. Need to check if leftSub == -1 or rightSub == -1 or height diff > 1
public boolean isBalanced(TreeNode root) {
return treeDepth(root) >= 0;
}
private int treeDepth(TreeNode root) {
// base case
if (root == null)
return 0;
// divide
int leftSubtree = treeDepth(root.left);
int rightSubtree = treeDepth(root.right);
// conquer
if (leftSubtree == -1 || rightSubtree == -1 || Math.abs(leftSubtree - rightSubtree) > 1) {
return -1;
} else {
return 1 + Math.max(leftSubtree, rightSubtree);
}
}
Analysis #2
From an industry stand point, -1 is very unclear and can be hard to maintain afterward. Java doesn't support returning a tuple (That's why python is op for interview). We need a structure to hold our information. A structure is useful when we need to return 2 or more values.
Better Code
// we want to return 2 values so we create this structure to simulate a tuple
private class ReturnType {
boolean isBalanced;
int depth; // max depth
ReturnType(boolean isBalanced, int depth) {
this.isBalanced = isBalanced;
this.depth = depth;
}
}
public boolean isBalanced(TreeNode root) {
return balanceHelper(root).isBalanced;
}
private ReturnType balanceHelper(TreeNode root) {
// base case
if (root == null)
return new ReturnType(true, 0);
// divide
ReturnType leftSubtree = balanceHelper(root.left);
ReturnType rightSubtree = balanceHelper(root.right);
// conquer
if (!leftSubtree.isBalanced || !rightSubtree.isBalanced
|| Math.abs(leftSubtree.depth - rightSubtree.depth) > 1) {
return new ReturnType(false, 1 + Math.max(leftSubtree.depth, rightSubtree.depth));
} else {
return new ReturnType(true, 1 + Math.max(leftSubtree.depth, rightSubtree.depth));
}
}
Time Complexity
The time is O(V) because we visit each node exactly once.