Leetcode 111 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.
def min_depth(root) return 0 if not root return min_depth(root.left) + 1 if not root.right return min_depth(root.right) + 1 if not root.left [min_depth(root.right), min_depth(root.left)].min + 1 end
方法二:BFS 结束条件是找到一个没有子树的node
class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 stack = [root] depth = 1 while True: stack_new = [] for node in stack: if not node.left and not node.right: return depth if node.right: stack_new.append(node.right) if node.left: stack_new.append(node.left) stack = stack_new depth += 1