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;
        }
        
    };
    
  • 相关阅读:
    游戏与必胜策略
    中国剩余定理
    中国剩余定理
    欧几里得和扩展欧几里得
    欧几里得和扩展欧几里得
    51nod 1028 大数乘法 V2
    51nod 1028 大数乘法 V2
    51nod 1029 大数除法
    51nod 1029 大数除法
    51nod 1166 大数开平方
  • 原文地址:https://www.cnblogs.com/virgildevil/p/12227899.html
Copyright © 2011-2022 走看看