• 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 ;
        }
    };
    

      

  • 相关阅读:
    [Debug]驱动程序调测方法与技巧
    [内核同步]自旋锁spin_lock、spin_lock_irq 和 spin_lock_irqsave 分析
    ios多线程-GCD基本用法
    用PHP抓取页面并分析
    IOS开发-KVC
    IOS开发-KVO
    JavaScript垃圾回收(三)——内存泄露
    JavaScript垃圾回收(二)——垃圾回收算法
    JavaScript垃圾回收(一)——内存分配
    JavaScript闭包(二)——作用
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3681838.html
Copyright © 2020-2023  润新知