[LeetCode][Java] Minimum Depth of Binary Tree
来源:互联网 发布:淘宝助手是干什么用的 编辑:程序博客网 时间:2024/06/05 18:51
题目:
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.
题意:
给定一棵二叉树,返回它的最小高度。
最小高度是指从根节点到最近的叶子节点的最短路径中的节点的数目。
算法分析:
* 借助堆
* 类似《Binary Tree Level Order Traversal》中的算法
* 出现下一层无自带的情况,立即退出,返回该层的层数
AC代码:
/** * 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) {int index=0;boolean flag=false;ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();ArrayList<Integer> list= new ArrayList<Integer>(); LinkedList<TreeNode> que = new LinkedList<TreeNode>(); if (root==null) return 0; que.add(root); while(que!=null) { TreeNode tem; int size=que.size(); list.clear(); for(int i=0;i<size;i++) { tem=que.poll(); list.add(tem.val); if(tem.left==null&&tem.right==null) { flag=true;//只要出现父节点无子节点的情况,就直接跳出,统计size break; } if(tem.left!=null) que.add(tem.left); if(tem.right!=null) que.add(tem.right); } res.add(new ArrayList<Integer>(list)); if(flag) return res.size(); else index=res.size(); } return index; }}
0 0
- [Leetcode] Minimum Depth of Binary Tree (Java)
- [LeetCode][Java] Minimum Depth of Binary Tree
- LeetCode|Minimum Depth of Binary Tree-java
- leetcode:Minimum Depth of Binary Tree 【Java】
- LeetCode 111 : Minimum Depth of Binary Tree (Java)
- Leetcode:111. Minimum Depth of Binary Tree(JAVA)
- leetcode-java-111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree【java】
- [leetcode]111. Minimum Depth of Binary Tree@Java解题报告
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- web.xml错误处理
- Java-发送邮件(附件、图片)---(一)概述
- 【工作拾遗】 weblogic节点服务启动问题记录
- 分解复杂判断
- xml布局内容总结(一)--Android
- [LeetCode][Java] Minimum Depth of Binary Tree
- 引入参数对象
- Apache Web Server -> httpd 的虚拟主机的配置
- 栈帧、局部变量表、操作数栈
- 笔试题程序练习
- Android Studio SDK 更新问题
- C++中static关键字的总结
- jquery模拟select
- JavaScript权威指南_133_第15章_脚本化文档_15.8-文档和元素的几何形状和滚动-文档坐标和视口坐标