forked from walnutown/CodingInTheDeep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.java
More file actions
61 lines (57 loc) · 1.52 KB
/
Copy pathBinaryTreeLevelOrderTraversal.java
File metadata and controls
61 lines (57 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
/*
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// same as CTCI ch4_4
// count the number of nodes in a level, time: O(n); space: O(b^d)
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (root == null)
return res;
Queue<TreeNode> qu = new LinkedList<TreeNode>();
qu.add(root);
int curr_num = 1, next_num = 0;
ArrayList<Integer> r = new ArrayList<Integer>();
while (!qu.isEmpty()){
TreeNode curr = qu.poll();
r.add(curr.val);
if (curr.left != null){
qu.add(curr.left);
next_num++;
}
if (curr.right != null){
qu.add(curr.right);
next_num++;
}
if (--curr_num == 0){
curr_num = next_num;
next_num = 0;
res.add(new ArrayList<Integer>(r));
r.clear();
}
}
return res;
}
}