tutorialcup
Minimum Depth of Binary Tree Leetcode Solution
In this problem, we need to find the length of the shortest path from the root to any leaf in a given binary tree. Note that the "length of the path" here means the number of nodes from the root node to the leaf node. This length is called Minimum Depth of A Binary Tree.
Example
Input
2
Explanation
The Shortest path is: 2 -> 1 , which is of length 2
Input
3
Explanation
The Shortest Path is: 1 -> 2 -> 3, of length 3
Approach(Recursive)
This problem is structurally same as finding the height of a binary tree but in this case, we need to find the minimum height/depth between the root and any leaf in the tree. We can retrieve the minimum depths of left and right subtrees of the root using Depth First Search(DFS) and then return the minimum of the two depths. We need to consider some cases when either of the left and right subtrees of a node is NULL. If the left subtree is NULL, it will return a height equal to 0 but as we have found no leaf in this subtree, so this 0 will be a wrong answer. Hence, we only need to call the recursive function when the node it is called upon is NOT null.
Algorithm
www.tutorialcup.com/leetcode-solutions/minimum-depth-of-b...
Minimum Depth of Binary Tree Leetcode Solution
In this problem, we need to find the length of the shortest path from the root to any leaf in a given binary tree. Note that the "length of the path" here means the number of nodes from the root node to the leaf node. This length is called Minimum Depth of A Binary Tree.
Example
Input
2
Explanation
The Shortest path is: 2 -> 1 , which is of length 2
Input
3
Explanation
The Shortest Path is: 1 -> 2 -> 3, of length 3
Approach(Recursive)
This problem is structurally same as finding the height of a binary tree but in this case, we need to find the minimum height/depth between the root and any leaf in the tree. We can retrieve the minimum depths of left and right subtrees of the root using Depth First Search(DFS) and then return the minimum of the two depths. We need to consider some cases when either of the left and right subtrees of a node is NULL. If the left subtree is NULL, it will return a height equal to 0 but as we have found no leaf in this subtree, so this 0 will be a wrong answer. Hence, we only need to call the recursive function when the node it is called upon is NOT null.
Algorithm
www.tutorialcup.com/leetcode-solutions/minimum-depth-of-b...