-
Notifications
You must be signed in to change notification settings - Fork 115
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
``` | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
## 二叉树 | ||
|
||
* [102.二叉树的最大深度](LeetCode/二叉树/102.二叉树的最大深度) | ||
* [104.二叉树的层序遍历](LeetCode/二叉树/104.二叉树的层序遍历) |
Empty file.