HDU 1710 二叉树的遍历

#include <iostream>
#include <stack>
using namespace std;

typedef struct Node
{
     Node *l,*r;    //struct Node 与 Node  均可以 
	 int num;
}*tree;

tree root;

tree creat(int a[],int b[],int n)
{
	tree ss;
	for (int i=0;i<n;i++)
	{
		if (a[0] == b[i])
		{
            ss = (tree)malloc(sizeof(Node));
			ss->num = b[i];
			ss->l=creat(a+1,b,i);
			ss->r=creat(a+i+1,b+i+1,n-i-1);
			return ss;
		}
	}
	return NULL;

}

void post_order(tree h)
{
     if (h !=NULL)     //if判断一定不能少,因为到叶子的地方就停止了,
     {
		post_order(h->l);
		post_order(h->r);
		if (root == h)
		{
			cout<<h->num<<endl;
		}
		else
		    cout<<h->num<<" ";
	 }
}

int main()
{
    int a[1000],b[1000],n,i;
	tree h;
	while (cin>>n)
	{
		for(i=0;i<n;i++)
		{
			cin>>a[i];
		}
		for (i=0;i<n;i++)
		{
			cin>>b[i];
		}
		root = h = creat(a,b,n);
		post_order(h);
	}
	return 0;
}


从先序遍历与中序遍历中得到根节点,再根据中序遍历中根的左边(左子树)与右边(右子树),再递归找根。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值