zoukankan      html  css  js  c++  java
  • 层次打印二叉树

    #include<vector>
    #include<queue>
    #include<string>
    #include<binaryNode.hpp>
    #include<iostream>
    #include<sstream>
    template<typename T>
    class traverse {
    public:
        using D = T::value_type;
        void print_tree() {
            std::queue<binaryNode<D>*>q;
            q.push(tree.root());
            while (!q.empty())
            {
                std::vector<binaryNode<D>*>vec;
                while (!q.empty()) { vec.push_back(q.front()); q.pop(); }
                std::string line = "                        ";
                for (auto i : vec)
                {
                    auto temp = i;
                    if (temp)
                    {
                        for (auto j = 0; j < inorder_vec.size(); ++j)
                        {
                            if (inorder_vec[j] == temp)
                            {
                                std::string str;
                                put << temp->data;
                                put >> str;
                                put.clear();
                                line.insert(j, str);
                                break;
                            }
                        }
                        if (temp->lson) q.push(temp->lson);
                        if (temp->rson) q.push(temp->rson);
                    }
                }
                std::cout << line << std::endl;
            }
    
    
        }
        traverse(T& tree) :tree(tree)
        {
            inorder_traverse(tree.root());
        }
    private:
        T &tree;
        std::stringstream put;
        std::queue<binaryNode<D>*> q;
        std::vector<binaryNode<D>*>inorder_vec;
        void inorder_traverse(binaryNode<D>* node)
        {
            if (!node)return;
            inorder_traverse(node->lson);
            inorder_vec.push_back(node);
            inorder_traverse(node->rson);
        }
    
    
    
    };

    所望隔山海
  • 相关阅读:
    redis
    基础加强(@注解)
    过滤器Filter
    监听器
    ajax
    Java 常用类Math、System、时间相关Calender和Date
    Java Object、Scanner、String 、生成jar包
    Java 内部类、eclipse、包
    Java 面向对象之抽象
    Java 面向对象三大特征之多态
  • 原文地址:https://www.cnblogs.com/otakus/p/14725274.html
Copyright © 2011-2022 走看看