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