-
Notifications
You must be signed in to change notification settings - Fork 15
/
binary-tree-level-order-traversal.java
110 lines (85 loc) · 2.62 KB
/
binary-tree-level-order-traversal.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// write your code here
// recursion version.
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
dfsHelper(res, root, 1);
return res;
}
public void dfsHelper(ArrayList<ArrayList<Integer>> res, TreeNode node, int level) {
if (node == null) {
return;
}
int size = res.size();
ArrayList<Integer> currentLevel = null;
if (size < level) {
currentLevel = new ArrayList<Integer>();
res.add(currentLevel);
} else {
// index start from 0.
currentLevel = res.get(level - 1);
}
currentLevel.add(node.val);
dfsHelper(res, node.left, level + 1);
dfsHelper(res, node.right, level + 1);
}
}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// write your code here
// iterative version.
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return res;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int size = 1;
while (!queue.isEmpty()) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
tempList.add(cur.val);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
size = queue.size();
res.add(tempList);
}
return res;
}
}