码迷,mamicode.com
首页 > 其他好文 > 详细

19.3.5 [LeetCode 103] Binary Tree Zigzag Level Order Traversal

时间:2019-03-05 11:02:29      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:display   pop   des   hide   splay   i++   click   example   lap   

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]
]
技术图片
 1 class Solution {
 2 public:
 3     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
 4         deque<TreeNode*>q,p;
 5         vector<vector<int>>ans;
 6         if (!root)return ans;
 7         int i = 0;
 8         q.push_back(root);
 9         ans.push_back(vector<int>());
10         ans[0].push_back(root->val);
11         while (!q.empty()) {
12             while (!q.empty()) {
13                 TreeNode*now;
14                 if (i % 2 == 0) {
15                     now = q.front(); q.pop_front();
16                 }
17                 else {
18                     now = q.back(); q.pop_back();
19                 }
20                 if (now->left) {
21                     if (i % 2 == 0)
22                         p.push_front(now->left);
23                     else
24                         p.push_back(now->left);
25                 }
26                 if (now->right) {
27                     if (i % 2 == 0)
28                         p.push_front(now->right);
29                     else
30                         p.push_back(now->right);
31                 }
32             }
33             if(!p.empty())
34                 ans.push_back(vector<int>());
35             while (!p.empty()) {
36                 q.push_back(p.front());
37                 ans[i+1].push_back(p.front()->val);
38                 p.pop_front();
39             }
40             i++;
41         }
42         return ans;
43     }
44 };
View Code

 

19.3.5 [LeetCode 103] Binary Tree Zigzag Level Order Traversal

标签:display   pop   des   hide   splay   i++   click   example   lap   

原文地址:https://www.cnblogs.com/yalphait/p/10475158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!