zoukankan      html  css  js  c++  java
  • 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]
    ]
    要注意读取的顺序,是折线。每次都应该按照不同的顺序。
    /**
     * 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> > re;
        vector<vector <TreeNode *> > t;
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            if( root != NULL)
            {
                vector<int> ve;
                ve.push_back(root->val);
                vector <TreeNode *> tr;
                tr.push_back(root->right);
                tr.push_back(root->left);
                re.push_back(ve);
                t.push_back(tr);
                get(0);
            }
            
            return re;
        }
        void get(int n)
        {
            vector<int> ve;
            vector <TreeNode *> tr;
            if(n%2 == 0)
            {
                vector<TreeNode *> tt;
                for(int i = 0 ; i < t[n].size();i++)
                {
                    if(t[n][i] != NULL)
                    {
                        ve.push_back(t[n][i]->val);
                        tt.push_back(t[n][i]->right);
                        tt.push_back(t[n][i]->left);
                    }
                }
                for(int i = tt.size()-1;i>=0;i--)
                tr.push_back(tt[i]);
                
            }
            else{
                vector<TreeNode *> tt;
                for(int i = 0 ; i < t[n].size();i++)
                {
    
                    if(t[n][i] != NULL)
                    {
                        ve.push_back(t[n][i]->val);
                        tt.push_back(t[n][i]->left);
                        tt.push_back(t[n][i]->right);
                    }
                }
                for(int i = tt.size()-1;i>=0;i--)
                    tr.push_back(tt[i]);
            }
            
            if(ve.size()==0)return;
            
            re.push_back(ve);
            t.push_back(tr);
            get(n+1);
            return ;
        }
    };
    

      

  • 相关阅读:
    桥接模式
    单例模式
    SpringAOP aspectJ ProceedingJoinPoint 获取当前方法
    springMVC实现文件下载
    JAVA的变量初始化类成员变量和局部变量区别
    JAVA枚举类型的应用
    linux下svn命令大全
    转:shell脚本的一些注意事项
    转: linux下不同服务器间数据传输(rcp,scp,rsync,ftp,sftp,lftp,wget,curl)
    TCP三次握手/四次挥手详解
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3681838.html
Copyright © 2011-2022 走看看