zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    201703-1 分蛋糕
    201812-2 小明放学
    201812-1 小明上学
    逆向_Easy_vb
    逆向_入门逆向
    代码审计_弱类型整数大小比较绕过
    代码审计_数组返回NULL绕过
    代码审计_md5()函数
    代码审计_urldecode二次编码绕过
    代码审计_extract变量覆盖
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812018.html
Copyright © 2011-2022 走看看