I tried this problem with Paul winkler. My approach was to define a recursion function inside of the main function and mutate a global depth variable, but as I worked through it realized I faced a challenge which was that I didn’t really have a way to make sure that the left and right nodes didn’t BOTH increment the global depth. I had sort of found a fake solution to this, which was incredibly stupid:
if (root){
let localDepth = globalDepth += 1
if (localDepth > globalDepth){
glovalDepth = localDepth
}
}
I’m…still not exactly sure what I was thinking here. This is a really verbose way of just saying globalDepth++ 😂
But clearly when I wrote it I thought that somehow I could trick logic into only incrementing under some special condition, which never seemed to show up.
Ultimately, I found that a pure functional recursive approach worked great! Here it is along with my psuedocode:
Time it took me to get to this code^: 26 minutes
Note
Can I do this without recursion? No I cannot. It would be useful to learn how to do that.
Despite the carnage I got when I ran this and generally got an extra increment for every generation of depth initially, I am proud of the eloquence of my final solution. If I just remove it from it’s parent function in which it’s needlessly encased, I get this:
Not bad! That’s probably the first time I’ve gotten to a five-line function on my own in less than half an hour.
It never ceases to amaze me the way code works - how much more available a 40 line function is than a four or five line solution, even though the latter looks so simple when I look at it.