zoukankan      html  css  js  c++  java
  • 剑指OFFER 按之字形顺序打印二叉树

    剑指OFFER 按之字形顺序打印二叉树

    套用 剑指OFFER 把二叉树打印成多行的代码,然后翻转一下奇数行即可

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
    
        vector<vector<int> > Print(TreeNode* pRoot) {
            if(pRoot==NULL)return vector<vector<int> >();
            queue<pair<TreeNode*,int> > que;//结点,层数
            vector<vector<int> > res;//返回的结果
            map<int,vector<int> >m;//层数--该层的所有结点
    
            que.push(pair<TreeNode*,int>(pRoot,0));
    
            while(!que.empty())
            {
                pair<TreeNode*,int> p = que.front();
                que.pop();
    
                m[p.second].push_back(p.first->val);
    
                if(p.first->left!=NULL){
                    que.push(pair<TreeNode*,int>(p.first->left,p.second+1));
                }
                if(p.first->right!=NULL){
                    que.push(pair<TreeNode*,int>(p.first->right,p.second+1));
                }
    
            }
            auto it = m.begin();
            while(it != m.end())
            {
                res.push_back(it->second);
                it++;
            }
            
            for(int i=0;i<res.size();i++)
            {
                if(i%2!=0)reverse(res[i].begin(),res[i].end());
            }
            
            return res;
        }
        
    };
    
  • 相关阅读:
    SpringBoot整合RabbitMq
    SpringBoot整合Mybatis
    Docker操作
    mysql高级复习
    mysql复习2
    springcloud复习2
    mysql复习1
    springcloud复习1
    JDBC(7)—DAO
    mysql报错:1130 -host 'localhost' is not allowed to connect to this mysql server
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12227899.html
Copyright © 2011-2022 走看看