难度中等178
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回锯齿形层次遍历如下:
[ [3], [20,9], [15,7] ]
解题思路:这道题在你掌握二叉树的层序遍历之后,现在你需要创建变量说明层数,在层数为偶数的时候进行头插,要不然就是尾插。
可能我的想法比较low,内存消耗还是比较大。
/**
* 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) {
List<List<Integer>> list = new ArrayList<>();
if(root == null)
return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ceng = 0;
while(!queue.isEmpty()){
List<Integer> list1 = new ArrayList<>();
++ceng;
int size = queue.size();
while(size>0){
TreeNode cur = queue.poll();
if(ceng % 2 == 0){
list1.add(0,cur.val);
}else{
list1.add(cur.val);
}
if(cur.left != null)
queue.offer(cur.left);
if(cur.right != null)
queue.offer(cur.right);
size --;
}
list.add(list1);
}
return list;
}
}