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.


题意:给一个二叉树,求出根节点到叶子节点(终端结点)的最短路径

解法:使用BFS广度优先遍历,记录层数,遇到左右同时为null,返回层数

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def minDepth(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: int
  12. """
  13. if(not root):
  14. return 0
  15. queue = [root]
  16. level = 1
  17. while(queue):
  18. count = len(queue)
  19. for i in range(0, count):
  20. node = queue.pop(0)
  21. if(not node.left and not node.right):
  22. return level
  23. if(node.left):
  24. queue.append(node.left)
  25. if(node.right):
  26. queue.append(node.right)
  27. level += 1






原文地址:https://www.cnblogs.com/xiejunzhao/p/7139049.html