算法题——Minimum Depth of Binary Tree(JAVA)
来源:互联网 发布:伪满洲国 知乎 编辑:程序博客网 时间:2024/06/06 07: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.
读题:
找出二叉树的最短深度。用广度优先搜索。
知识储备:
广度优先搜索树
1. 从根节点开始,搜索他的子节点;
2. 搜索所有处在第二层子节点他们的子节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则该节点到根节点的路径为最短路径。
Queue队列:
主要用到的函数
解题思路:
1. 用队列来存储每一层的节点;
2. 从根节点开始,把每一层的节点放入队列,记录队列大小,即该层的节点数;
2. 当循环次数小于该层节点数,从队列的头部开始,如果该节点有子节点,则将他的子节点放进队列尾部,然后移除该节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则结束。
提交代码:
/** * 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; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); int depth = 1; queue.add(root); TreeNode head = root; while (true) { int size = queue.size(); for (int i = 0; i < size; i++) { if (head.left == null && head.right == null) { return depth; } else { if (head.left != null) { queue.add(head.left); } if (head.right != null) { queue.add(head.right); } queue.remove(); head = queue.peek(); } } depth++; } }}
0 0
- 算法题——Minimum Depth of Binary Tree(JAVA)
- 算法系列——Minimum Depth of Binary Tree
- LeetCode111—Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree——LeetCode(Easy)
- [Leetcode] Minimum Depth of Binary Tree (Java)
- Minimum Depth of Binary Tree Java
- Minimum Depth of Binary Tree (Java)
- Minimum Depth of Binary Tree Java
- [LeetCode][Java] Minimum Depth of Binary Tree
- LeetCode|Minimum Depth of Binary Tree-java
- (java)Minimum Depth of Binary Tree
- leetcode:Minimum Depth of Binary Tree 【Java】
- minimum-depth-of-binary-tree java code
- Leetcode:111. Minimum Depth of Binary Tree(JAVA)
- minimum-depth-of-binary-tree(Leetcode)
- LeetCode——Minimum Depth of Binary Tree
- LeetCode——Minimum Depth of Binary Tree
- leetcode 111 —— Minimum Depth of Binary Tree
- java中解析HTML的方法:Jsoup和正则表达式
- C#之基础语法
- react native 遇到的问题整理
- 椒盐噪声加噪的实现原理
- caffe训练我们自己的数据
- 算法题——Minimum Depth of Binary Tree(JAVA)
- gdb调式
- Struts2运行流程分析
- java 基本数据类型、包装类、字符串、数组之间的类型转换
- pat L1-001. Hello World
- 极大似然估计法
- c++ STL list容器
- API Guides之App Resources
- windows使用docker新开窗口error