zoukankan      html  css  js  c++  java
  • LeetCode_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,#,#,15,7},
    
    
        3
       / \
      9  20
        /  \
       15   7
    
    return its zigzag level order traversal as:
    
    [
      [3],
      [20,9],
      [15,7]
    ]
    

      和level order traversal 唯一的不同是,偶数行逆序输出,逆序可是使用stack来实现。其他的实现和level order实现大同小异

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            vector<vector<int>> result ;
            if(root ==NULL) return result;
            std::queue<TreeNode *> q,p;
            std::stack<int> kit;
            vector<int> mResult;
            bool f = false ;
            q.push(root);
            while(!q.empty()){
              
               mResult.clear();
               if(f)
               {
                while(!q.empty()){            
                    root = q.front(); q.pop();
                    kit.push(root->val);
                    if(root->left)
                        p.push(root->left);
                    if(root->right)
                        p.push(root->right);
                }
                while(!kit.empty())
                {
                  mResult.push_back(kit.top());
                  kit.pop();
                }
                f = false;
               }else{
               
                  while(!q.empty()){            
                    root = q.front(); q.pop();
                    mResult.push_back(root->val);
                    if(root->left)
                        p.push(root->left);
                    if(root->right)
                        p.push(root->right);
                  }
                  f = true ;
               }
               result.push_back(mResult);
                while(!p.empty()){
                q.push(p.front());
                p.pop();            
               }
               
            }
            
            return result;
            
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    汉字词组换行
    C#中获取Excel文件的第一个表名
    SQL查找某一条记录的方法
    C#数据库连接字符大全
    整理的asp.net资料!(不得不收藏)
    母版页的优点,及母版页与内容页中相互访问方法
    13范式
    使用 Jackson 树连接线形状
    word2007,取消显示回车符
    三张表之间相互的多对多关系
  • 原文地址:https://www.cnblogs.com/graph/p/3019921.html
Copyright © 2011-2022 走看看