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,null,null,15,7],
3
/ \ 9 20
/ \ 15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
解题思路:
如果知道二叉树层序便利就知道用一个队列可以层序便利,那么如果把每层的节点装到一个list中,关键就在于用另一个队列装子节点。于是解法如下:
/** * 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<List<Integer>> resultlist = new ArrayList<>();
Queue queue1 = new LinkedList<Integer>();
Queue queue2 = new LinkedList<Integer>();
if(root==null)
return resultlist;
queue1.add(root);
List<Integer> templist = new ArrayList<Integer>();
templist.add(root.val);
resultlist.add(templist);
while(!(queue1.peek()==null&&queue2.peek()==null)){
templist = new ArrayList<Integer>();
while(queue1.peek()!=null){
TreeNode temp = (TreeNode)queue1.poll();
if(temp.left!=null){
queue2.add(temp.left);
templist.add(temp.left.val);
}
if(temp.right!=null){
queue2.add(temp.right);
templist.add(temp.right.val);
}
}
if(templist.size()!=0&&templist!=null){
resultlist.add(templist);
}
while(queue2.peek()!=null){
queue1.add(queue2.poll());
}
}
return resultlist;
}
}