zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    使用Pandas DataFrames在Python中绘制条形图
    在Pandas DataFrames中选择行和列使用iloc,loc和ix
    如何使用[] 、. loc,iloc,.at和.iat
    Pandas 分类数据
    按索引和值对Pandas DataFrame进行排序
    可能需要的建议
    时间线
    第四章-赶路
    第三章-担忧
    lipo命令拆分、合并iOS静态库
  • 原文地址:https://www.cnblogs.com/yalphait/p/10475158.html
Copyright © 2011-2022 走看看