LeetCode111 计算二叉树的最小深度,很好的体现出了广度优先遍历和深度优先遍历的区别。
对于二叉树来说,深度优先遍历就是前序、中序、和后序遍历,而广度优先遍历就是层次遍历。
当求解一些最小之类的题目时,广度优先往往比深度优先遍历更为有效,因为它很多时候无需遍历完所有节点就可以退出遍历。
深度优先遍历(后序)
public class Solution111 {public int minDepth(TreeNode root) {if(root == null) return 0;if(root.left == null && root.right == null) return 1;if(root.left == null) return minDepth(root.right) + 1;if(root.right == null) return minDepth(root.left) + 1;return Math.min(minDepth(root.left), minDepth(root.right)) + 1;}}
广度优先遍历(层次)
public class Solution111_version2 {public int minDepth(TreeNode root) {if (root == null) {return 0;}Queue<QueueNode> queue = new LinkedList<>();queue.offer(new QueueNode(root, 1));while(!queue.isEmpty()){QueueNode queueNode = queue.poll();TreeNode treeNode = queueNode.treeNode;int depth = queueNode.depth;if(treeNode.left == null && treeNode.right == null) return depth;if(treeNode.left != null)queue.offer(new QueueNode(treeNode.left, depth + 1));if(treeNode.right != null)queue.offer(new QueueNode(treeNode.right, depth + 1));}return 0;}class QueueNode {TreeNode treeNode;int depth;QueueNode(TreeNode treeNode, int depth){this.treeNode = treeNode;this.depth = depth;}}}
