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
  • 相关阅读:
    Nginx应用详解及配置
    mongodb复制+分片集原理
    memcached架构及缓存策略
    redis数据类型
    redis数据库安装 redis持久化及主从复制
    shell脚本-正则、grep、sed、awk
    kvm虚拟机管理基础
    kvm热添加和热迁移
    zabbix调用api检索方法
    kubernetes deployment升级和回滚
  • 原文地址:https://www.cnblogs.com/yalphait/p/10475158.html
Copyright © 2011-2022 走看看