(模板)已知二叉树先序(后序)中序,求这棵二叉树

这种题型为考研常考题型。看这张图就比较好理解了,先序的第一个元素或后序的最后一个元素为当前子树的根

确认先序/后序的根后,我们遍历中序序列寻找根在中序序列中的位置,上图中为ink,那么ink左边的序列位于二叉树的左子树部分,

ink右边的序列位于二叉树的右子树部分

我们确认左子树部分k个元素,就可以确定子树区间了

先序左子树区间 [POSTL+1,POSTL+k]

先序右子树区间 [POSTL+k+1,POSTR]

中序左子树区间 [inkL, k-1]

中序右子树区间 [k+1 inkR]

后序左子树区间 [POSTL,POSTL+k-1]

后序右子树区间 [POSTL+k,POSTR-1]

下面给出模板

类似的习题见:https://blog.youkuaiyun.com/alex1997222/article/details/86600218

Node* CreateTree(int postL, int postR, int inL, int inR) {
	if (postL > postR) return nullptr;
	int curPostRoot = postArrays[postR];
    //确定根的值
	Node* root = new Node(curPostRoot);
	int curInRoot = -1;
	int k;
    //在中序中查找根,确定根的位置
	for (k = inL; k <= inR; ++k) {
		if (inArrays[k] == curPostRoot) {
			curInRoot = inArrays[k];
			break;
		}
	}
	if (curInRoot == -1) return nullptr;
    //后序遍历
	int numleft = k - inL;  
	root->lchild = CreateTree(postL,postL+numleft-1,inL,k-1);
	root->rchild = CreateTree(postL+numleft,postR-1,k+1,inR);
    //先序遍历
    int numleft = k - inL;  
	root->lchild = CreateTree(postL+1,postL+numleft,inL,k-1);
	root->rchild = CreateTree(postL+numleft+1,postR,k+1,inR);

	return root;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值