面试题:Minimum Depth of Binary Tree
来源:互联网 发布:恋狱月狂病 知乎 编辑:程序博客网 时间:2024/05/29 17:12
这个也好顺,8分钟做完,没有报错。
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.
/**
* Definition for binary tree
* 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;
}
if (isLeaf(root)) {
return 1;
}
int result = 1;
List<TreeNode> nodePool = new ArrayList<TreeNode>();
nodePool.add(root);
while (true) {
List newNodePool = new ArrayList<TreeNode>();
for (TreeNode node : nodePool) {
if (isLeaf(node)) {
return result;
} else {
if (node.left != null) {
newNodePool.add(node.left);
}
if (node.right != null) {
newNodePool.add(node.right);
}
}
}
nodePool = newNodePool;
result ++;
}
}
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
}
- 面试题:Minimum Depth of Binary Tree
- Leetcode 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
- 线程局部存储实现
- 奇葩实现SlidingMenu,不得不转
- Oracle 自定义TYPE 的几种用法
- STM8S TIM1时钟分频
- C++实现计数排序
- 面试题:Minimum Depth of Binary Tree
- 线程的创建和启动---实现Runnable接口创建线程类
- 怎么在eclipse里,让ctrl+鼠标点击,跳到android class里去。
- generate apk QT5.2 folder
- pig语法学习 FOREACH GENERATE group AS
- temp2_asset
- linux开发超经典书籍推荐
- TMS320C6713烧写Flash的通用方法
- 多个目录之间的切换-pushd、popd、dirs