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

-55

u/MrPancholi Jun 19 '21

It does work, but I just thought that the tuple thing I did was a little weird.

I suck with algorithms so I though this was pretty far form the ideal solution.

54

u/Cotspheer Jun 19 '21

Well thats where you were wrong and right at the same time kiddo.

4

u/cyanNodeEcho Jun 19 '21 edited Jun 20 '21

okay i had to think, is it bc this solution only supports even powers of 2?

which are exponentially sparse so as n -> large this algo will give wrong answer almost with probabliltiy 1?

if absolutely balanced was in the question seems like u might be able to

if left.height == right.height:
        return height + 1 


else:
        0

if i were trying to be cheaky in python:

 return l.height == r.height and l.height or 0 + 1

which would eliminate the tuple, but require wrapping the length as boole

also still learning please be gentle (θ‿θ)


edit: okay i looked at the official solution, def wasnt clear to me that max height wouldnt obscure relative differences in height.

but i understand now. still confused why you wouldnt just calc (max, min) and then wrap that in a compare in a different function, seems so much more understandable... but im not super well versed 😅

4

u/Cotspheer Jun 19 '21

As far my computer science skills go, its seems to be solid. To know if the tree itself is balanced one has to calculate the left and the right height of the tree and this for each subtree. https://www.programiz.com/dsa/balanced-binary-tree Basically this implementation in typescript.

The tuple thing is a convenient thing to return the depth and if it's balanced. I see this often in c# but I dislike the use of tuples because they don't provide a meaning like an interface or class would. So please do this for the ones coming after you. Nothing wrong to use a proper named return type.

1

u/cyanNodeEcho Jun 19 '21 edited Jun 20 '21

i think if else would return the height if it were balanced, max height is good as well if unbalanced?

3

u/btwiusearch Jun 19 '21
getHeightBalanceTupl

The weird thing is that the e is missing.