HDU1710 Binary Tree Traversals(二叉树遍历)

HDU1710-Binary Tree Traversals

题目描述
给定一棵二叉树的先序和中序遍历结果,求后序。

Input
输入包含多组数据. 第一行一个n表示二叉树内的节点数 (1<=n<=1000). 下面两行分别表示先序遍历和中序遍历的序列 。
Output
对于每组数据在一行内输出该二叉树后序遍历序列.
Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1

在中序里找前序第一个pre[0],找到的位置i即为根节点,那么中序里[0,i-1]即是左子树,[i+1,n-1]即为右子树(n为中序序列的长度,下标从0开始的),同时前序的第一个元素(即根节点)就没用了,因为根节点已经构造出来了,那么就从pre[1]开始把前序序列pre分成两部分,怎么分呢?就是前半部分的长度和[0,i-1]长度相等,后半部分和[i+1,l-1]长度相等,然后这就有了两对分半的前序序列和后序序列,然后用这两对分别左右递归构造左右子树。
注意:每次分的前序和中序序列都必须保证长度相等!
AC代码

#include<iostream>
#include<algorithm>
using namespace std;
int f;
int pre[1005], mid[1005];
struct BiNode
{
	int data;
	BiNode *lchild, *rchild;
};

BiNode *NewNode(int x)
{
	BiNode *t = new BiNode;
	t->lchild = t->rchild = NULL;
	t->data = x;
	return t;
}

BiNode *CreateTree(int *pre, int l1, int *mid, int l2)
{
	int i, j, k;
	for (i = 0; i < l2; i++)
	{
		if (pre[0] == mid[i])break;
	}
	BiNode *t = NewNode(mid[i]);
	if (i > 0)
	{
		t->lchild = CreateTree(pre + 1, i, mid, i);

	}
	if (i < l2 - 1)
	{
		t->rchild = CreateTree(pre + i + 1, l2 - i - 1, mid + i + 1, l2 - i - 1);
	}
	return t;
}

void Print(BiNode *T)
{
	if (T == NULL)return;
	Print(T->lchild);
	Print(T->rchild);
	if (f)
		cout << " ";
	f = 1;
	cout << T->data;
}
int main()
{
	int n;
	while (cin>>n)
	{
		for (int i = 0; i < n; i++)
			cin >> pre[i];
		for (int i = 0; i < n; i++)
			cin >> mid[i];
		BiNode *root;
		root = CreateTree(pre, n, mid, n);
		f = 0;
		Print(root);
		cout << endl;
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值