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

4

u/F54280 Jun 20 '21 edited Jun 20 '21

Yeah, looks good to me. Only improvement is to stop the height difference and just use leftHeight == rightHeight instead of the ugly Math.abs and the extra variable. But that’s almost nothing.

Edit: as pointed by /u/SuperSmurfen, I am wrong

12

u/SuperSmurfen Jun 20 '21

Except the height is allowed to differ by one. Take this balanced tree for example:

A
  \
    B

leftHeight == 0, rightHeight = 1, yet it is balanced. That's why the awkward abs check is required.

2

u/F54280 Jun 20 '21

Excellent catch, thx.