题目
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
思路
- 层序遍历思路,偶数列反转
java
/**
* 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>> zigzagLevelOrder(TreeNode root) {
if(root == null){
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> list = new LinkedList<>();
list.offer(root);
boolean normalOrder = true;
while(!list.isEmpty()){
int size = list.size();
ArrayList<Integer> level = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode cur = list.poll();
level.add(cur.val);
if(cur.left != null){
list.offer(cur.left);
}
if(cur.right != null){
list.offer(cur.right);
}
}
if (normalOrder) {
res.add(level);
}else {
Collections.reverse(level);
res.add(level);
}
normalOrder = !normalOrder;
}
return res;
}
}