Statementâ–¼
You are given the root
of a binary tree, and your task is to determine the maximum depth of this tree. The maximum depth of a binary tree is determined by the count of nodes found on the longest path from the root node to the farthest leaf node.
Constraints:
The number of nodes in the tree is in the range
[1,500]. −100≤ Node.data
≤100
Solution
The approach which we will be using to solve this problem is iterative depth-first search. We visit all the nodes of the given binary tree, starting from the root
node. A stack is used to keep track of the visited nodes along with the depth at which they are located. Once all the nodes of the tree have been traversed, we return the maximum depth max_depth
we have calculated so far.
To obtain this solution, the following procedure can be adopted:
We initialize a stack
nodes_stack
to keep track of nodes for exploration. In thenodes_stack
, we start with a tuple containing theroot
node and a depth of1 .Initialize a variable
max_depth
with0 to keep track of the maximum depth that is calculated so far.Iterate over
nodes_stack
and pop its top element. If this node has a left child, create a tuple consisting of the left child node, and an incremented depth(depth + 1)
, and push this tuple onto the stack. Likewise, a similar tuple is added to the stack if the right child exists.When a leaf node, i.e., a node with no left or right child, is encountered, check if
depth
is greater thanmax_depth
. In that case, updatemax_depth
to the value ofdepth
.After traversing all nodes, return
max_depth
, representing the maximum depth of the binary tree.
Let’s look at the following illustration to get a better understanding of the solution: