This seems like a pretty straightforward problem: we essentially want to just count the maximum number of levels that the tree has. There's several ways to do this, but we'll need to traverse the tree.
Given that it's a binary tree, this means that there's up to two paths to move -- left
and right
. This fact simplifies things a bit, as traversal just requires navigating two children at each node.
During traversal, we can detect a leaf either when there is no left
or right
:
xxxxxxxxxx
if (!node.left && !node.right) {
return;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment