leetcode 111.Minimum Depth of Binary Tree-树最小深度|深度遍历|广度遍历
2016-04-26 23:39
441 查看
原题链接:111.Minimum Depth of Binary Tree
【思路】
采用 dfs深度优先:
cases passed. Runtime: 1
ms Your runtime beats 12.17% of javasubmissions.
【补充】
采用 bfs 非递归实现:
cases passed. Runtime: 1 ms Your runtime beats 12.17% of javasubmissions.
【思路】
采用 dfs深度优先:
public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left != null && root.right != null) //当根左右均不为空时,遍历左右子树,取最小值 return Math.min(minDepth(root.left), minDepth(root.right)) + 1; return Math.max(minDepth(root.left), minDepth(root.right)) + 1; //当左右子树有一边为空时,要去最大值 }41 / 41 test
cases passed. Runtime: 1
ms Your runtime beats 12.17% of javasubmissions.
【补充】
采用 bfs 非递归实现:
public int minDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<TreeNode>(); int layer = 1; queue.add(root); while (!queue.isEmpty()) { int curCount = queue.size(); //本层节点数 while (curCount-- > 0) { //将下一层节点存入 queue 中 TreeNode temp = queue.poll(); if (temp.left == null && temp.right == null) return layer; if (temp.left != null) queue.add(temp.left); if (temp.right != null) queue.add(temp.right); } layer++; } return layer; }41 / 41 test
cases passed. Runtime: 1 ms Your runtime beats 12.17% of javasubmissions.
相关文章推荐
- Vijos1776关押罪犯
- 最长回文子串-Manacer算法
- JAVA每日总结
- JVM 类型的生命周期学习
- Redis的AOF持久化-Redis学习笔记四
- sass、less和stylus的安装使用和入门实践
- c++上机报告4
- Java 接口和抽象类区别
- linux修改用户目录文件名
- Mysql5.6配置文件详解
- 贪心算法经典例子
- Atitit.增强系统稳定性----虚拟内存的设置
- 工具函数(二)
- Atitit.增强系统稳定性----虚拟内存的设置
- c++ 11(四)
- 为什么跑步比赛是逆时针跑?
- C++实验4-穷举法解决组合问题
- c++课后作业4
- 第 10 章 表单元素[下]
- Atitit.md5 实现原理