103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
与上一题类似
不同在于,奇数层 正着存,偶数层,倒着存。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import queue class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: q = queue.Queue() if root: q.put(root) res = [] level = 0 while q.qsize(): sz = q.qsize() cur = [] level+=1 for i in range(sz): top = q.get() cur.append(top.val) if top.left: q.put(top.left) if top.right : q.put(top.right) if level%2==0: res.append(cur[::-1]) else: res.append(cur) return res
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; if(root == nullptr) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int cnt = q.size(); res.push_back(vector<int>()); for(int i = 0 ; i< cnt; ++i) { auto node = q.front(); q.pop(); if(res.size()%2 != 0) { res.back().push_back(node->val); } else { res.back().insert(res.back().begin(),node->val); } if(node->left!=nullptr) q.push(node->left); if(node->right!=nullptr) q.push(node->right); } } return res; } };
1 class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 5 if(root==null) return res; 6 int flag =1; 7 queue.add(root); 8 while (!queue.isEmpty()) { 9 int levlnum = queue.size(); 10 List<Integer> res_temp = new ArrayList<Integer>(); 11 for (int i = 0;i<levlnum ;i++ ){ //把每层的左右节点都保存到queue里 12 //并讲当层的值从queue里弹出,加到res_temp 中 13 if(queue.peek().left!=null) queue.add(queue.peek().left); 14 if(queue.peek().right!=null) queue.add(queue.peek().right); 15 if(flag==1) 16 res_temp.add(queue.poll().val); 17 else 18 res_temp.add(0,queue.poll().val); 19 } 20 res.add(res_temp); 21 flag = 1-flag; 22 } 23 return res; 24 }