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] ]
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(root != null){
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(root.val);
lists.add(arrayList);
addLeftARight(root.left, root.right, lists,1);
}
return lists;
}
public void addLeftARight(TreeNode left, TreeNode right, List<List<Integer>> lists, int index){
if(left == null && right == null) return;
if(index == lists.size()){
ArrayList<Integer> arrayList = new ArrayList<Integer>();
lists.add(arrayList);
}
if(left == null){
lists.get(index).add(right.val);
addLeftARight(right.left,right.right, lists, index+1);
}else if(right == null){
lists.get(index).add(left.val);
addLeftARight(left.left,left.right, lists, index+1);
}else{
lists.get(index).add(left.val);
lists.get(index).add(right.val);
addLeftARight(left.left,left.right, lists, index+1);
addLeftARight(right.left,right.right, lists, index+1);
}
return;
}
}