zoukankan      html  css  js  c++  java
  • 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]
    ]


    在102的基础上稍加改动即可
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            
           queue<TreeNode*> q;
           queue<int> q2;
           vector<vector<int> > ans;
           if(root==NULL)
               return ans;
           q.push(root);q2.push(0);
           vector<int> res;
           int j=-1;
           int tag = 0;
           while(!q.empty())
           {
               TreeNode* term = q.front();
               int i = q2.front();
               if(i==j+2)
               {
                   if(tag==1)
                   {
                       vector<int> a;
                       for(int i=res.size()-1;i>=0;i--)
                       {
                           a.push_back(res[i]);
                       }
                       tag=0;
                       ans.push_back(a);
                   }
                   else
                   {
                       ans.push_back(res);
                       tag=1;
                   }
                   res.clear();
                   j++;
               }
               res.push_back(term->val);     
               q.pop();q2.pop();
               if(term->left!=NULL)
               { q.push(term->left);q2.push(i+1);}
               if(term->right!=NULL)
               { q.push(term->right);q2.push(i+1);}
           }
           if(!res.empty())
           {
               
                   if(tag==1)
                   {
                       vector<int> a;
                       for(int i=res.size()-1;i>=0;i--)
                       {
                           a.push_back(res[i]);
                       }
                       tag=0;
                       ans.push_back(a);
                   }
                   else
                       ans.push_back(res);
                
           }
               
            
           return ans;      
            
        }
    };
  • 相关阅读:
    python 生成器 迭代器
    廖---高级特性 切片 迭代 列表生成式
    汉诺塔
    廖---函数
    廖---控制流
    廖---list tuple dic set
    廖---字符串和编码
    MySQL常见的三种存储引擎
    mysql悲观锁以及乐观锁总结和实践
    数据库事务的四大特性以及事务的隔离级别
  • 原文地址:https://www.cnblogs.com/dacc123/p/9211029.html
Copyright © 2011-2022 走看看