Length 1:41Loading the video
Loading the video
How tall is a binary tree? Each node asks its two children how deep they go, takes the bigger answer and adds one. A few lines of recursion visit every node once.
Narrated by an AI voice.
How tall is a binary tree?
That is LeetCode problem one hundred four, and we will solve it in JavaScript.
The depth of a tree is the number of nodes on the longest path.
That path starts at the root, at the top, and goes down to the farthest leaf.
A leaf is a node with no children.
Here is our example tree.
The root holds three.
Its children are nine and twenty.
Twenty has two children, fifteen and seven.
The longest path is three, twenty, fifteen.
That path has three nodes, so the answer is three.
Here is the key idea.
A node does not need to see the whole tree.
It asks its left child and its right child how deep they go.
Then it takes the bigger answer and adds one for itself.
Every recursion needs a place to stop.
If a node is empty, there is nothing there, so its depth is zero.
In JavaScript, an empty child is null.
Here is the whole function.
First, if the root is null, return zero.
Next, find the depth of the left subtree.
Then find the depth of the right subtree.
Finally, return one plus the larger of the two.
Let us run it on our tree.
Nine, fifteen and seven are leaves.
Their children are null, so each leaf returns one.
Twenty gets one from each side, so it returns two.
The root gets one from nine and two from twenty.
It returns one plus two, which is three.
How fast is this?
We visit every node once, so the time grows in a straight line with the number of nodes.
The extra memory is the call stack, one frame for each level we go down.
For a tree shaped like a long chain, that is one frame per node.
You can also count levels without recursion.
Keep a queue of the nodes on one level.
Process the whole level, add the next level, and count one each time.
To sum up, the depth of a tree is one plus the deeper of its two subtrees, and an empty tree has depth zero.
BFS, DFS and topological sort: how they work
How to walk a graph or a grid level by level (BFS) or path by path (DFS), and how to put tasks in an order that respects every rule (topological sort).
Type any algorithm, interview problem or system, and get your own narrated video.
3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing
Make a video
Length 1:41
Length 2:02
Length 1:13