Find Minimum Depth Binary Tree
MediumPractice library · +20 XPrecursiontreesbfs
Given the root of a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. A leaf node is a node with no children.
Input
The input represents a binary tree using a level-order traversal. Null nodes are represented by the string 'null'. For example, [3,9,20,null,null,15,7] represents a tree.
Output
Print a single integer representing the minimum depth of the binary tree.
Constraints
The number of nodes in the tree is between 0 and 200000. Node values are integers.
Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
[3,9,20,null,null,15,7]
Output
2
The shortest path is 3 -> 9, so the minimum depth is 2.
Example 2
Input
[2,null,3,null,4,null,5,null,6]
Output
5
The shortest path is 2 -> 3 -> 4 -> 5 -> 6, so the minimum depth is 5.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
[3,9,20,null,null,15,7]
Example 2 input
[2,null,3,null,4,null,5,null,6]