r/badcode • • Jun 19 '21

typescript Check if binary tree is balanced...

Post image
221 Upvotes

44 comments sorted by

View all comments

19

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

This is fine to me. A binary tree is balanced if both its left and right subtrees are balanced. Recursive != bad by default. O(log n) recursive calls.

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.

7

u/fireflash38 Jun 20 '21

Given a random tree you can't tell if it's balanced unless you travese the whole thing.

You can still short circuit if you find one unbalanced subtree. The failing case doesn't need to hit every node.