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;
            
        }
    };
    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    Less 文档查看心得
    Jquery+SlideDown+在IE7和IE6中的bug
    Highcharts 图表库
    安卓 日常问题 工作日志6
    安卓 日常问题 工作日志5
    安卓 日常问题 工作日志 3
    安卓 日常问题 工作日志 2
    安卓 日常问题 工作日志
    新的开始 安卓工程师
    2018.4.16号 我也不知道应该写点什么
  • 原文地址:https://www.cnblogs.com/graph/p/3019921.html
Copyright © 2011-2022 走看看