This algorithm will ALWAYS visit every node. So the lower, upper, and average are the same.
Stopping at the first unbalanced node would change the bounds to:
Lower 1: constant in the case that in the case where it is the first node that you check (technically 3rd node, but that is still constant time)
Upper N: if the tree is balanced you still have to check every node
Average lg(n): When you find an unbalanced node, you can skip checking all of the other children and parents. This relies on checking that left is balanced first, and skipping the recursive call on the right when needed.
const [leftHeight,isLeftBalanced] = getHeightBalanceTupl(root.left); if (!isLeftBalanced) return [leftHeight,isLeftBalanced]; const [rightHeight,isRightBalanced] = getHeightBalanceTupl(root.right); if (!isRightBalanced) return [rightHeight,isRightBalanced];
This does break the calculation for the height of the tree, but there is no way to do both. (Ignoring memorization techniques.)
2
u/seemslikesalvation Jun 19 '21
You’re right; l meant recursive depth is log N.