Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Context that can be derived from the question?
Longest / farthest leaf nodes can be found using depth first search method.
There are 3 primary way to solve DFS:
PreOrder
InOrder (Go down 1 direction until it hits null, then come back and grab it's direct parent
PostOrder (Go down both direction and only when both direction are null grab it's parent)
Le't use one of these
PreOrder (Grab as you)
Tree:
1
/ \
2 3
/ \
4 5
PreOrder: [1, 2, 4, 5, 3]
InOrder
(Go down 1 direction until it hits null, then come back and grab it's direct parent)
Tree:
1
/ \
2 3
/ \
4 5
InOrder: [4, 2, 5, 1, 3]
PostOrder:
Go down both direction and only when both direction are null grab it's parent
Tree:
1
/ \
2 3
/ \
4 5
PostOrder: [4, 5, 2, 3, 1]
We know that to calculate the max depth of binary tree we need to find out the both left and right sub tree from root.
So it naturally aligns with PostOrder DFS.
The question is what will help us only traverse or account the the longest distance only?
function postOrder(node, result){
if(node.left){
postOrder(node.left, result)
}
if(node.right){
postOrder(node.right, result)
}
result.push(node.value)
return result
}
For us to calculate:
The maximum depth of a binary tree is the length of the longest path from the root node to any leaf node.
1. Break Down the Problem
PostOrder traversal:
Left subtree depth is calculated first.
Right subtree depth is calculated next.
Current node depth is calculated as 1 + max(leftDepth, rightDepth).
Also shift focus on depth calculation:
If a node is null, return 0 (base case for leaf nodes).
Thus we can conclude:
function postOrder(node, length){
if(!node){
return 0
}
let leftDepth = postOrder(node.left)
let rightDepth = postOrder(node.right)
return 1 + Math.max(leftDepth, rightDepth )
}
Context that can be derived from the question?
So it naturally aligns with PostOrder DFS.
The question is what will help us only traverse or account the the longest distance only?
For us to calculate:
The maximum depth of a binary tree is the length of the longest path from the root node to any leaf node.
1. Break Down the Problem
PostOrder traversal:
Thus we can conclude:
This can be further simplified as:
Now let's calculate the Big O Notation:
Potential Follow Up Question To Answer:
Let me know what you think about the answer to these question?
#blind75 #tree #traversal