【PAT-A1086】Tree Traversals Again(二叉树重建)

【分析】

这道题就是典型的二叉树重建和遍历。从中序遍历的出入栈操作,得到先序序列和中序序列,重建树结构,再得到后序序列。

【代码】

#include <cstdio> 
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 35;
int n = 0;
vector<int> pre, in, post;
stack<int> st;

struct Node
{
	Node* lchild, *rchild;
	int w;
};

Node* create(int preL, int preR, int inL, int inR) {
	if (preR < preL) {
		return NULL;
	}

	Node* root = new Node;
	root->w = pre[preL];
	// 在中序序列中找到根结点下标
	int k = 0;
	for (int i = inL; i <= inR; i++)
	{
		if (in[i] == pre[preL]) {
			k = i;
			break;
		}
	}
	int Lnum = k - inL, Rnum = inR - k;

	root->lchild = create(preL + 1, preL + Lnum, inL, k - 1);
	root->rchild = create(preL + Lnum + 1, preR, k + 1, inR);
	return root;
}

void postOrder(Node* root) {
	if (root == NULL) {
		return;
	}
	postOrder(root->lchild);
	postOrder(root->rchild);
	post.push_back(root->w);
}

int main() {
	// 输入并获取先序和中序序列
	
	scanf("%d", &n);
	string str;
	int index;
	for (int i = 0; i < 2 * n; i++)
	{
		cin >> str;
		if (str == "Push") {
			cin >> index;
			pre.push_back(index);
			st.push(index);
		}
		else
		{
			int top = st.top();
			st.pop();
			in.push_back(top);
		}
	}

	// 先序后序重建二叉树
	Node* root = create(0, n - 1, 0, n - 1);
	postOrder(root);
	// 输出后序序列
	for (int i = 0; i < n; i++)
	{
		if (i != 0) {
			printf(" ");
		}
		printf("%d", post[i]);
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值