-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102.binary-tree-level-order-traversal.java
More file actions
68 lines (48 loc) · 1.52 KB
/
Copy path102.binary-tree-level-order-traversal.java
File metadata and controls
68 lines (48 loc) · 1.52 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Pair{
TreeNode root;
int ind;
Pair(TreeNode root, int ind){
this.root = root;
this.ind = ind;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null)
return res;
Queue<Pair> que = new LinkedList<Pair>();
que.offer(new Pair(root, 0));
while(!que.isEmpty()){
Pair tnp = que.poll();
if(res.size() < tnp.ind+1)
res.add(new ArrayList<Integer>());
res.get(tnp.ind).add(tnp.root.val);
if(tnp.root.left != null)
que.offer(new Pair(tnp.root.left, tnp.ind+1));
if(tnp.root.right != null)
que.offer(new Pair(tnp.root.right, tnp.ind+1));
}
return res;
}
// public void dfs(List<List<Integer>> res, TreeNode root, int ind){
// if(root == null)
// return;
// res.get
// }
}