r/badcode • • Jun 19 '21

typescript Check if binary tree is balanced...

Post image
221 Upvotes

44 comments sorted by

View all comments

137

u/SuperSmurfen Jun 19 '21 edited Jun 19 '21

What is bad about this? Looks pretty readable to me, good variable names (all though perhaps a bit verbose), and it's pretty much just the standard O(n) algorithm

www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced

0

u/[deleted] Jun 19 '21

[deleted]

7

u/RFC793 Jun 19 '21

Who cares, it is just used internally by the recursion. You don’t have to provide or be concerned by it with the wrapper at the bottom.

0

u/[deleted] Jun 19 '21

[deleted]

6

u/symberke Jun 20 '21

At least at a cursory glance at the problem you definitely need both pieces of information. With height defined as the maximum distance to a leaf node you can't determine if a tree descending from a given node is balanced given only the heights of its two children. Similarly you can't determine if the tree is balanced given only the fact that its two child trees are balanced.