r/badcode • • Jun 19 '21

typescript Check if binary tree is balanced...

Post image
221 Upvotes

44 comments sorted by

View all comments

Show parent comments

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.

2

u/seemslikesalvation Jun 19 '21

You’re right; l meant recursive depth is log N.

7

u/icendoan Jun 19 '21

Recursive calls is O(n): consider the degenerate tree with only left children. The full left hand side gets counted here, which is one for each node.

4

u/seemslikesalvation Jun 19 '21 edited Jun 19 '21

Shit, it’s been a long time since I studied DSA. Log N would be the lower bound. Is that big-Omega?

1

u/paulsmithkc 👨‍🏫 Jun 20 '21 edited Jun 20 '21

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.)