Solution: Maximum Depth of Binary Tree
Let's solve the Maximum Depth of Binary Tree problem using the Tree Depth-First Search pattern.
We'll cover the following
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
Node.data
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_stackto keep track of nodes for exploration. In thenodes_stack, we start with a tuple containing therootnode and a depth of. Initialize a variable
max_depthwithto keep track of the maximum depth that is calculated so far. Iterate over
nodes_stackand 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
depthis greater thanmax_depth. In that case, updatemax_depthto 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:
1 of 15
2 of 15
3 of 15
4 of 15
5 of 15
6 of 15
7 of 15
8 of 15
9 of 15
10 of 15
11 of 15
12 of 15
13 of 15
14 of 15
15 of 15
Let’s implement the algorithm as discussed above.
Time complexity#
The time complexity of the given code is
Space complexity#
The space complexity of the given code is root.
Maximum Depth of Binary Tree
Binary Tree Right Side View