链接:https://www.nowcoder.com/questionTerminal/47e1687126fa461e8a3aff8632aa5559
来源:牛客网
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树之字形层序遍历的结果是
[
[3],
[20,9],
[15,7]
]
示例1
输入
{1,#,2}
输出
[[1],[2]]
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
if(root == null) return new ArrayList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean flag = true;
while(!q.isEmpty()){
int count = q.size();
ArrayList<Integer> tmp = new ArrayList<>();
while(count > 0){
TreeNode cur = q.poll();
//层序遍历代码
if(flag){
tmp.add(cur.val);
}else{
tmp.add(0, cur.val);
}
if(cur.left != null){
q.offer(cur.left);
}
if(cur.right != null){
q.offer(cur.right);
}
count--;
}
flag = !flag;
res.add(tmp);
}
return res;
}
}