forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.java
More file actions
34 lines (34 loc) · 1.09 KB
/
BinaryTreeLevelOrderTraversal.java
File metadata and controls
34 lines (34 loc) · 1.09 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//O(N)
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
nodes.add(root);
while(nodes.peek() != null){
LinkedList<TreeNode> tmp = new LinkedList<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
while(nodes.peek() != null){
TreeNode current = nodes.pop();
if(current.left != null)
tmp.add(current.left);
if(current.right != null)
tmp.add(current.right);
result.add(current.val);
}
results.add(result);
nodes = tmp;
}
return results;
}
}