zoukankan      html  css  js  c++  java
  • leetcode-Binary Tree Zigzag Level Order Traversa

    /**
     * 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)
        {
            vector<vector<int>> result;
            vector<int> vec;
            result.clear();
            if(NULL==root)
                return result;
            deque<TreeNode*>deq;
            deq.clear();
            deq.push_back(root);
            int len1 = 1;
            int len2 ;
            bool dir = true;
            while(!deq.empty())
            {
                len2 = 0;
                if(dir)
                {
                    while(len1--)
                    {
                        vec.push_back(deq.front()->val);
                        if(deq.front()->left!=NULL)
                        {
                               deq.push_back(deq.front()->left);
                               len2++;
                        }
                        if(deq.front()->right!=NULL)
                        {
                             deq.push_back(deq.front()->right);
                             len2++;
                        }
                         deq.pop_front();
                    }
                    dir = !dir;
                }
                else
                {
                    while(len1--)
                    {
                        vec.push_back(deq.back()->val);
                        if(deq.back()->right!=NULL)
                        {
                             deq.push_front(deq.back()->right);
                             len2++;
                        }
                        if(deq.back()->left!=NULL)
                        {
                               deq.push_front(deq.back()->left);
                               len2++;
                        }
                       
                         deq.pop_back();
                    }
                    dir = !dir;
                }
                result.push_back(vec);
                len1=len2;
                vec.clear();
            }
            return result;
        }
    };


    1. 双端队列完成

    2. 记住clear()

    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    重写GridView(转载)
    《Windows Communication Foundation之旅》系列之二(转载)
    C++类的继承与多重继承的访问控制(转载)
    准备出发
    10月8日 多云
    081014 曇後雨
    关于SQL Server 2005 Reporting Services的几点设置
    081007 浓雾
    081003 晴
    10月6日 上班
  • 原文地址:https://www.cnblogs.com/vintion/p/4116881.html
Copyright © 2011-2022 走看看