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]
]
Idea: Breadth-first search. Use a queue to maintain the next level.
Time: O(n) Space: O(n)
Code:
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(root==null)
return result;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty())
{
int number=queue.size();
List<Integer> tmp=new ArrayList<Integer>();
for(int i=0;i<number;i++)
{
TreeNode cur=queue.poll();
tmp.add(cur.val);
if(cur.left!=null)
queue.offer(cur.left);
if(cur.right!=null)
queue.offer(cur.right);
}
result.add(tmp);
}
return result;
}
}
No comments:
Post a Comment