-
Notifications
You must be signed in to change notification settings - Fork 0
/
102.二叉树的层次遍历.java
54 lines (46 loc) · 1.21 KB
/
102.二叉树的层次遍历.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.LinkedList;
/*
* @lc app=leetcode.cn id=102 lang=java
*
* [102] 二叉树的层次遍历
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<>();
if(root == null){
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
TreeNode temp = null;
List<Integer> levelList = null;
while(!queue.isEmpty()){
int queueSize = queue.size();
levelList = new ArrayList<Integer>();
for(int i = 0; i < queueSize; i++){
temp = queue.poll();
if(temp.left != null) {
queue.offer(temp.left);
}
if(temp.right!= null){
queue.offer(temp.right);
}
levelList.add(temp.val);
}
result.add(levelList);
}
return result;
}
}