19.3.5 [LeetCode 103] Binary Tree Zigzag Level Order Traversal

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.3.5 [LeetCode 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]
]
技术图片
 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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 103

LeetCode ???103??? ?????????????????????????????????

leetcode103

103. leetcode笔记(1~60)

5-103-(LeetCode-8) 字符串转换整数 (atoi)

leetcode-----103. 二叉树的锯齿形层次遍历