Leetcode - Minimum Depth of Binary Tree
2016-04-19 21:11
267 查看
Question
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.
Java Code
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //版本一: DFS,递归遍历每一个节点,取根节点到所有叶子节点距离的最小值 public int minDepth(TreeNode root) { if(root == null) return 0; else if(root.left != null && root.right != null) return Math.min(minDepth(root.left), minDepth(root.right)) + 1; else if(root.left != null && root.right == null) return minDepth(root.left) + 1; else if(root.left == null && root.right != null) return minDepth(root.right) + 1; else return 1; } //版本二: BFS,逐层遍历,找到第一个叶子节点即结束 public int minDepth(TreeNode root) { if(root == null) return 0; LinkedList<TreeNode> list = new LinkedList<>(); list.add(root); list.add(null); TreeNode temp; int level = 0; while(list.size() != 1) { level++; while ((temp = list.pollFirst()) != null) { if(temp.left != null && temp.right != null) { list.add(temp.left); list.add(temp.right); }else if(temp.left != null && temp.right == null) list.add(temp.left); else if(temp.left == null && temp.right != null) list.add(temp.right); else return level; } list.add(null); } return level; }
说明
版本一的代码可以参考另一个类似的题目Maximum Depth of Binary Tree,本题不能通过仅仅把Math.max函数改成Math.min来实现,因为本题求的是根节点与最近的叶子节点之间的距离,当二叉树中非叶子节点出现空子节点时,直接选择其左右子树中较小的深度就会出错(但直接选择其左右子树中较大的深度却不会出错,why?)版本二的代码采取层次遍历的方法,这样可以尽快找到最先出现叶子节点的层,也即找到了树的最小深度,避免了继续遍历该层以下的节点,具体细节可以参考另一个类似的题目Binary Tree Level Order Traversal
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- c# in depth的泛型实现实例代码
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- leetcode----Longest Substring Without Repeating Characters
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays