CH6.3.3二叉树重建(给出先序中序遍历,求后序遍历)

书上的方法更简单,没有构造二叉树,直接将后序遍历顺序存在ans数组中,然后输出

#include<stdio.h>
#include<string.h>
char input[100];
struct Node
{
	char ch;
	Node* left;
	Node* right;
};
bool ok;
Node* root;
Node* newnode(char c, Node* pl, Node* pr)
{
	Node* pnd = new Node;
	pnd->ch = c;
	pnd->left = pl;
	pnd->right = pr;
	return pnd;
}
void del_tree(Node* subroot)
{
	if(!subroot) return;
	del_tree(subroot->left);
	del_tree(subroot->right);
	delete subroot;
}
char preorder[100];
char inorder[100];
char* find(char ch, char* start, char * end) 
{
	char* p;
	for(p = start; p < end; ++p)
	{
		if(*p == ch) 
			break;
	}
	return p;
}
Node* build_tree(char* prestart, char* instart, int len)
{
	if(len == 0)
		return 0;
	char* inparent = find(prestart[0], instart, instart+len);
	int firstlen = inparent-instart;  
    // firstlen is the left subtree's 'length'
	Node* left = build_tree(prestart+1, instart, firstlen);
	Node* right = build_tree(prestart+firstlen+1, inparent+1, len-firstlen-1);
	return newnode(prestart[0], left, right);
}
void postorder(Node* subroot)
{
	if(!subroot) return;
	postorder(subroot->left);
	postorder(subroot->right);
	putchar(subroot->ch);
}
int main()
{
	//
	freopen("input.txt", "r", stdin);
	while(scanf("%s%s", preorder, inorder) == 2)
	{
		root = build_tree(preorder, inorder, strlen(preorder));
		postorder(root);
		del_tree(root);
		putchar('\n');
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值