给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3<br /> / \<br /> 9 20<br /> / \<br /> 15 7<br />返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
int cnt = 0; //层数
queue.add(root);
while(!queue.isEmpty()){
cnt++;
int n = queue.size();
List<Integer> list = new ArrayList<>();
while(n-- > 0){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
if((cnt & 1) == 0) Collections.reverse(list);
res.add(list);
}
return res;
}
}