Minimum Depth of Binary Tree
来源:互联网 发布:java web service 编辑:程序博客网 时间:2024/06/04 19:40
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.
Tree Depth-first SearchHave you met this question in a real interview?
思路:同样还是树的递归问题,dfs深度遍历一下就行,这类问题的解法比较固定。本题用到优先队列(默认从小到大),所以直接出队,就是最小深度值。
代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); public int minDepth(TreeNode root) { if(root==null) return 0; dfs(root,0); return queue.poll(); } public void dfs(TreeNode root,int count){ if(root==null){ return; }else{ count++; if(root.left==null&&root.right==null){ queue.add(count); return; } } dfs(root.left,count); dfs(root.right,count); }}
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; //这里bfs没用队列,是因为要对每一层的节点进行判断,用队列体现不出每一层的处理 //除非向队列中存入键值对,键是树节点,值是这个节点所在的层数,感觉有点麻烦 ArrayList<TreeNode> last = new ArrayList<TreeNode>(); last.add(root); int count = 1; while(!last.isEmpty()){ ArrayList<TreeNode> cur = new ArrayList<TreeNode>(); for(TreeNode treeNode:last){ if(treeNode.left==null&&treeNode.right==null){ return count; }else{ if(treeNode.left!=null){ cur.add(treeNode.left); } if(treeNode.right!=null){ cur.add(treeNode.right); } } } last = cur; count++; } return count; }}
之前的求二叉树镜像的就可以用BFS,对每一层的每个节点交换其左右子节点。那里不需要对层处理,所以直接可以用队列queue。思想都是类似的
参考博客:http://blog.csdn.net/sbitswc/article/details/26526031
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Phone模块后续文章说明
- 《C语言及程序设计》实践参考——点结构体
- 1. 从线性代数谈起-
- android studio教程及android环境搭建
- linux ftp命令使用
- Minimum Depth of Binary Tree
- HTML实体符号代码速查表
- 《C语言及程序设计》实践参考——体重监测器
- 表单元素
- JAVA-1-学习历程1:基础知识1
- 《C语言及程序设计》实践参考——个税计算器之码数分离
- 图片展示
- 如何让vim编辑器永久显示行号
- 将Eclipse中的项目迁移到Android Studio中的方法