请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
ArrayList<List<Integer>> result=new ArrayList<List<Integer>>();
if(root==null){
return result;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
int num=1;
while(!queue.isEmpty()){
int size=queue.size();
List<Integer> currentlevel=new ArrayList<Integer>();
for(int i=0;i<size;i++){
TreeNode head=queue.poll();
currentlevel.add(head.val);
if(head.left!=null){
queue.offer(head.left);
}
if(head.right!=null){
queue.offer(head.right);
}
}
if(num%2==0){
for(int i=0,j=currentlevel.size()-1;i<j;i++,j--){
int res=currentlevel.get(i);
currentlevel.set(i,currentlevel.get(j));
currentlevel.set(j,res);
}
}
num++;
result.add(currentlevel);
}
return result;
}
}