zoukankan      html  css  js  c++  java
  • L2-006. 树的遍历

    时间限制
    400 ms
    内存限制
    65536 kB
    代码长度限制
    8000 B
     
     

    给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

    输入格式:

    输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

    输出格式:

    在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

    输入样例:
    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    
    输出样例:
    4 1 6 3 5 7 2
    #include "iostream"
    #include "cmath"
    #include "cstdio"
    #include "map"
    #include "queue"
    #include "string"
    #include "cstring"
    using namespace std;
    
    bool fist;
    struct tree_node{
        int value;
        tree_node *leftchild;
        tree_node *rightchild;
        tree_node(){
            leftchild==NULL;
            rightchild=NULL;
        }
    };
    /**
        知后序遍历,中序遍历,建立二叉树
    */
    tree_node * build_tree(int post[],int in[],int lenght)
    {
        if(lenght==0)return NULL;
        int pos;
        for(pos=0;pos<lenght;pos++)
        {
            if(in[pos]==post[lenght-1])break;
        }
        tree_node * temp=new tree_node;
        temp->value=post[lenght-1];
        temp->leftchild=build_tree(post,in,pos);
        temp->rightchild=build_tree(post+pos,in+pos+1,lenght-pos-1);
        return temp;
    }
    
    
    ///层次遍历
    void dfs(tree_node *root)
    {
        queue<tree_node *>Q;
        while(!Q.empty())Q.pop();
        Q.push(root);
        while(!Q.empty())
        {
            root=Q.front();
            Q.pop();
           if(fist==false)
            {
                cout<<root->value;
                fist=true;
            }
            else
            {
                cout<<" "<<root->value;
            }
            if(root->leftchild!=NULL)Q.push(root->leftchild);
            if(root->rightchild!=NULL)Q.push(root->rightchild);
        }
        cout<<endl;
    }
    int main()
    {
        int n,post[50],in[50];
        while(~scanf("%d",&n))
        {
            for(int i=0;i<n;i++)scanf("%d",&post[i]);
            for(int i=0;i<n;i++)scanf("%d",&in[i]);
            tree_node* root=build_tree(post,in,n);
            //system("pause");
            dfs(root);
        }
        return 0;
    }
  • 相关阅读:
    laravel5.* 生成key
    Laravel 调试利器 Laravel Debugbar 扩展包安装及使用教程
    JS相关
    Git常用命令(全)
    linux添加计划任务
    30个php操作redis常用方法代码例子(转载)
    获取服务器IP和客户端IP
    PHP-redis中文文档(相关)
    常用算法排序
    软件下载(汇总)
  • 原文地址:https://www.cnblogs.com/kimsimple/p/6456087.html
Copyright © 2011-2022 走看看