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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<TreeNode> tree1 =new ArrayList <TreeNode> ();
List<List<Integer>> ret = new ArrayList <List<Integer>> ();
List<List<Integer>> ret2 = new ArrayList <List<Integer>> ();
if(root==null)return ret;
tree1.add(root);
while(tree1.size()>0){
List<TreeNode> tree2 =new ArrayList <TreeNode> ();
List <Integer> a = new ArrayList <Integer> ();
for(int i = 0;i<tree1.size();i++){
a.add(tree1.get(i).val);
if(tree1.get(i).left!=null)tree2.add(tree1.get(i).left);
if(tree1.get(i).right!=null)tree2.add(tree1.get(i).right);
}
tree1=tree2;
ret2.add(a);
}
// for(int i=ret2.size()-1;i>=0;i--){
// ret.add(ret2.get(i));
// }
return ret2;
}
}