111. Minimum Depth of Binary Tree
2016-06-09 22:36
211 查看
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层次遍历吧。找到第一个叶子节点,返回深度即可。
DFS遍历也可以,遇到叶子节点就看看深度是不是比当前最小值更小。
public class Solution {
int min=Integer.MAX_VALUE;
public int minDepth(TreeNode root)
{
if(root==null)
return 0;
inorder(root, 1);
return min;
}
public void inorder(TreeNode t,int deep)
{
if(t.left!=null)
inorder(t.left,deep+1);
if(t.left==null&&t.right==null)
min=Math.min(min, deep);
if(t.right!=null)
inorder(t.right,deep+1);
}
}
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
BFS层次遍历吧。找到第一个叶子节点,返回深度即可。
ArrayDeque<TreeNode> deque; ArrayDeque<Integer> deepdeq; public int minDepth(TreeNode root) { if(root==null) return 0; deque=new ArrayDeque<>(); deepdeq=new ArrayDeque<>(); deque.add(root); deepdeq.add(1); while(!deque.isEmpty()) { TreeNode t=deque.poll(); int deep=deepdeq.poll(); if(t.left==null&&t.right==null) return deep; if(t.left!=null) { deque.add(t.left); deepdeq.add(deep+1); } if(t.right!=null) { deque.add(t.right); deepdeq.add(deep+1); } } return -1; }
DFS遍历也可以,遇到叶子节点就看看深度是不是比当前最小值更小。
public class Solution {
int min=Integer.MAX_VALUE;
public int minDepth(TreeNode root)
{
if(root==null)
return 0;
inorder(root, 1);
return min;
}
public void inorder(TreeNode t,int deep)
{
if(t.left!=null)
inorder(t.left,deep+1);
if(t.left==null&&t.right==null)
min=Math.min(min, deep);
if(t.right!=null)
inorder(t.right,deep+1);
}
}
相关文章推荐
- Java序列化与反序列化
- 深入理解CSS中的定位(position)
- 一个关于JS作用域链的例子
- 一个web项目web.xml的配置中<context-param>配置作用
- POJ1503
- C++ sizeof关键字的使用总结
- c++点滴
- C++走向远洋——67(项目二、洗牌)
- ajax笔记
- LeetCode:Combination Sum III
- 110. Balanced Binary Tree
- 《JavaScript学习笔记》:第一个面向对象的程序
- C++复习1.const用法
- poj3281Dining
- android ui 练习
- WindowsServer2012 搭建多台Tomcat
- 为什么我的hosts文件修改无效?
- HttpURLConnection、Handler、新闻客户端案例、get和post提交数据
- [线性常微分方程][5]SPECIAL CASES REPEATED AND ZERO EIGENVALUES
- arp欺骗进行流量截获-2