難度中等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;
}
}