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.
思路,判断每层节点是否都有孩子,如果左右孩子都为空,则跳出循环,返回树的高度。
class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ from collections import deque if not root: return 0 queue = deque([root]) flag = 'flag' queue.append(flag) mindepth = 1 while queue: node = queue.popleft() if node == flag : mindepth += 1 if not queue: break queue.append(flag) else: if not node.left and not node.right: return mindepth if node.left: queue.append(node.left) if node.right: queue.append(node.right)