Skip to content

Commit

Permalink
yoyiyi
Browse files Browse the repository at this point in the history
  • Loading branch information
yoyiyi committed Feb 22, 2021
1 parent b7718e2 commit 8c5966f
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
58 changes: 58 additions & 0 deletions 算法/LeetCode/二叉树/102.二叉树的层序遍历.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#### [题目](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)

给你一个二叉树,请你返回其按 **层序遍历** 得到的节点值。 (即逐层地,从左到右访问所有节点)。



**示例:**
二叉树:`[3,9,20,null,null,15,7]`,

```
3
/ \
9 20
/ \
15 7
```

返回其层序遍历结果:

```
[
[3],
[9,20],
[15,7]
]
```

## 解法

层序遍历就要想到队列。

```java
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<>();
List<List<Integer>> ret = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> temp = new ArrayList<>();
for(int i = 0;i < size; i++){
TreeNode tn = queue.poll();
temp.add(tn.val);
if(tn.left != null){
queue.add(tn.left);
}
if(tn.right != null){
queue.add(tn.right);
}
}
ret.add(temp);
}
return ret;
}
}
```

4 changes: 4 additions & 0 deletions 算法/leetcode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 二叉树

* [102.二叉树的最大深度](LeetCode/二叉树/102.二叉树的最大深度)
* [104.二叉树的层序遍历](LeetCode/二叉树/104.二叉树的层序遍历)
Empty file added 算法/剑指Offer.md
Empty file.

0 comments on commit 8c5966f

Please sign in to comment.