LeetCode Minimum Depth of Binary Tree
LeetCode-solving-Minimum Depth of Binary Tree
Original question
Calculate the minimum height of a binary tree, that is, the number of nodes passing through the path from the root node to the nearest leaf node.
Note:
None
Example:
Input:
3 / \ 9 20 / \ 15 7 / 14
Output: 2
Solutions
You can achieve this through Tree breadth-first Traversal of Binary Tree Level Order Traversal. In the process of breadth-first Traversal, the height of each layer is increased by one. If a node is a leaf node, the current height is the minimum height.
AC Source Code
# Definition for a binary tree node.class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 depth, curr_level = 0, [root] while curr_level: depth += 1 next_level = [] for n in curr_level: left, right = n.left, n.right if left is None and right is None: return depth if left: next_level.append(left) if right: next_level.append(right) curr_level = next_level return depthif __name__ == "__main__": None