Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created October 23, 2020 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuntalchandra/2cf4c22a9c30a0c4a35c04a658a14349 to your computer and use it in GitHub Desktop.
Save kuntalchandra/2cf4c22a9c30a0c4a35c04a658a14349 to your computer and use it in GitHub Desktop.
Minimum Depth of Binary Tree
"""
Given 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.
Note: A leaf is a node with no children.
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack, min_depth = [(1, root)], float('inf')
while stack:
depth, tree = stack.pop()
children = [tree.left, tree.right]
if not any(children):
min_depth = min(depth, min_depth)
for child in children:
if child:
stack.append((depth + 1, child))
return min_depth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment