-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal2.java
More file actions
36 lines (34 loc) · 1.01 KB
/
Copy pathBinaryTreeLevelOrderTraversal2.java
File metadata and controls
36 lines (34 loc) · 1.01 KB
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
/**
* 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>> levelOrderBottom(TreeNode root) {
if(root == null) return Collections.emptyList();
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
Queue<TreeNode> p = new ArrayDeque<>();
List<List<Integer>> result = new ArrayList<>();
List<Integer> layer = new ArrayList<>();
while(!q.isEmpty()) {
TreeNode t = q.poll();
layer.add(t.val);
if(t.left != null) p.offer(t.left);
if(t.right != null) p.offer(t.right);
if(q.isEmpty()) {
Queue<TreeNode> k = q;
q = p;
p = k;
result.add(new ArrayList<>(layer));
layer.clear();
}
}
Collections.reverse(result);
return result;
}
}