zoukankan      html  css  js  c++  java
  • A1020 Tree Traversals [中序后序建树]

    在这里插入图片描述
    题目大意:给你中序后序,要求输出层序。

    #include<iostream>
    #include<vector>
    #include<queue>
    using namespace std;
    const int maxn = 50;
    struct node
    {
    	int data;
    	node* left, * right;
    };
    int pre[maxn], in[maxn], post[maxn];
    int n;
    node* create(int postl, int postr, int inl, int inr)
    {
    	if (postl > postr)
    		return NULL;
    	node* root = new node;
    	root->data = post[postr];
    	int i;
    	for (i = inl; i <= inr; i++)
    	{
    		if (in[i] == post[postr])
    			break;
    	}
    	int numLeft = i - inl;
    	root->left = create(postl, postl + numLeft-1, inl, i - 1);
    	root->right = create(postl + numLeft, postr - 1, i + 1, inr);
    	return root;
    }
    int num = 0;
    void  bfs(node* root)
    {
    	queue<node*>q;
    	q.push(root);
    	while (!q.empty())
    	{
    		node* now = q.front();
    		q.pop();
    		cout << now->data;
    		num++;
    		if (num < n) cout << " ";
    		if (now->left != NULL) q.push(now->left);
    		if (now->right != NULL) q.push(now->right);
    	}
    }
    int main()
    {
    	node* T;
    	cin >> n;
    	for (int i = 0; i < n; i++)
    		cin >> post[i];
    	for (int i = 0; i < n; i++)
    		cin >> in[i];
    	T = create(0,n-1,0,n-1);
    	bfs(T);
    	return 0;
    }
    
  • 相关阅读:
    Python—模块
    Python之路_Day5
    Python之路_Day4
    Py获取本机指定网卡的ip地址
    Python之路_Day3
    Python之路—Day2作业
    Python之路—Day2
    Python之路—Day1作业
    Python之路—Day1
    Python数据类型
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812019.html
Copyright © 2011-2022 走看看