True that for recursive != bad, but this is still O(n) it visits every node once. Which makes sense. Given a random tree you can't tell if it's balanced unless you travese the whole thing.
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.)
17
u/KlzXS Jun 19 '21
True that for recursive != bad, but this is still O(n) it visits every node once. Which makes sense. Given a random tree you can't tell if it's balanced unless you travese the whole thing.