• A1086 Tree Traversals Again [前序中序建树]


    在这里插入图片描述

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<cstring>
    using namespace std;
    const int maxn = 31;
    struct node
    {
    	int data;
    	node* left;
    	node* right;
    };
    int pre[maxn], in[maxn], post[maxn];
    int n;
    node* create(int prel, int prer, int inl, int inr)
    {
    	if (prel > prer)
    		return NULL;
    	node* root = new node;
    	root->data = pre[prel];
    	int i;
    	for (i = inl; i <= inr; i++)
    	{
    		if (in[i] == pre[prel])
    			break;
    	}
    	int numleft = i - inl;
    	root->left = create(prel+1, prel + numleft , inl, i - 1);
    	root->right = create(prel + numleft+1, prer, i + 1, inr);
    	return root;
    }
    int num = 0;
    void postorder(node* root)
    {
    	if (root == NULL)
    		return;
    	postorder(root->left);
    	postorder(root->right);
    	cout << root->data;
    	num++;
    	if (num < n)
    		cout << " ";
    }
    int main()
    {
    	cin >> n;
    	char str[5];
    	stack<int>st;
    	int x, preindex=0, inindex = 0;
    	for (int i = 0; i < 2 * n; i++)
    	{
    		cin >> str;
    		if (strcmp(str, "Push") == 0)
    		{
    			cin >> x;
    			pre[preindex++] = x;
    			st.push(x);
    		}
    		else
    		{
    			in[inindex++] = st.top();
    			st.pop();
    		}
    	}
    	node* root = create(0, n - 1, 0, n - 1);
    	postorder(root);
    	return 0;
    }
    
  • 相关阅读:
    Activator.CreateInstance 反射实例化对象
    MVC Form提交
    Redis 下载
    List<T> 序列化与反序列化
    快速反射DataTable
    数据库特性
    javascript判断文件大小
    MD5
    HttpHelper
    cacheHelper
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812018.html
Copyright © 2020-2023  润新知