-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution32-3.java
More file actions
49 lines (45 loc) · 1.57 KB
/
Solution32-3.java
File metadata and controls
49 lines (45 loc) · 1.57 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
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 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>> rowList = new ArrayList<>();
if (root == null) {
return rowList;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (!stack1.isEmpty()) {
List<Integer> colList = new ArrayList<>();
while (!stack1.isEmpty()) {
TreeNode node = stack1.pop();
colList.add(node.val);
if (node.left != null) {
stack2.push(node.left);
}
if (node.right != null) {
stack2.push(node.right);
}
}
rowList.add(colList);
} else {
List<Integer> colList = new ArrayList<>();
while (!stack2.isEmpty()) {
TreeNode node = stack2.pop();
colList.add(node.val);
if (node.right != null) {
stack1.push(node.right);
}
if (node.left != null) {
stack1.push(node.left);
}
}
rowList.add(colList);
}
}
return rowList;
}
}