LeetCode111 计算二叉树的最小深度,很好的体现出了广度优先遍历和深度优先遍历的区别。
对于二叉树来说,深度优先遍历就是前序、中序、和后序遍历,而广度优先遍历就是层次遍历。
当求解一些最小之类的题目时,广度优先往往比深度优先遍历更为有效,因为它很多时候无需遍历完所有节点就可以退出遍历。

深度优先遍历(后序)

  1. public class Solution111 {
  2. public int minDepth(TreeNode root) {
  3. if(root == null) return 0;
  4. if(root.left == null && root.right == null) return 1;
  5. if(root.left == null) return minDepth(root.right) + 1;
  6. if(root.right == null) return minDepth(root.left) + 1;
  7. return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  8. }
  9. }

广度优先遍历(层次)

  1. public class Solution111_version2 {
  2. public int minDepth(TreeNode root) {
  3. if (root == null) {
  4. return 0;
  5. }
  6. Queue<QueueNode> queue = new LinkedList<>();
  7. queue.offer(new QueueNode(root, 1));
  8. while(!queue.isEmpty()){
  9. QueueNode queueNode = queue.poll();
  10. TreeNode treeNode = queueNode.treeNode;
  11. int depth = queueNode.depth;
  12. if(treeNode.left == null && treeNode.right == null) return depth;
  13. if(treeNode.left != null)
  14. queue.offer(new QueueNode(treeNode.left, depth + 1));
  15. if(treeNode.right != null)
  16. queue.offer(new QueueNode(treeNode.right, depth + 1));
  17. }
  18. return 0;
  19. }
  20. class QueueNode {
  21. TreeNode treeNode;
  22. int depth;
  23. QueueNode(TreeNode treeNode, int depth){
  24. this.treeNode = treeNode;
  25. this.depth = depth;
  26. }
  27. }
  28. }