mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #632 from ColorQian/master
添加 0102.二叉树的层序遍历.md文件 中的 111.二叉树的最小深度 的java代码
This commit is contained in:
@ -1623,6 +1623,43 @@ public:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
|
||||||
|
public int minDepth(TreeNode root){
|
||||||
|
if (root == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
Queue<TreeNode> queue = new LinkedList<>();
|
||||||
|
queue.offer(root);
|
||||||
|
int depth = 0;
|
||||||
|
|
||||||
|
while (!queue.isEmpty()){
|
||||||
|
|
||||||
|
int size = queue.size();
|
||||||
|
depth++;
|
||||||
|
|
||||||
|
TreeNode cur = null;
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
cur = queue.poll();
|
||||||
|
|
||||||
|
//如果当前节点的左右孩子都为空,直接返回最小深度
|
||||||
|
if (cur.left == null && cur.right == null){
|
||||||
|
return depth;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cur.left != null) queue.offer(cur.left);
|
||||||
|
if (cur.right != null) queue.offer(cur.right);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return depth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Python 3:
|
Python 3:
|
||||||
|
Reference in New Issue
Block a user