已知后序与中序输出前序

78 篇文章 1 订阅

参考链接:https://www.liuchuo.net/archives/2090

                https://blog.csdn.net/qq_29762941/article/details/80676658

已知后序与中序输出前序(先序):
后序:3, 4, 2, 6, 5, 1(左右根)
中序:3, 2, 4, 1, 6, 5(左根右)

分析:通过递归实现。因为后序的最后一个总是根结点,在中序通过该根结点确定左右子树,并通过start和end分别标出后序与中序左右子树范围。最后对左子树与右子树使用同样的方法。

实现代码如下:

#include <cstdio>
using namespace std;

int post[] = {3, 4, 2, 6, 5, 1};
int in[] = {3, 2, 4, 1, 6, 5};

void pre(int startPost,int endPost,int startInorder, int endInorder){
	if(startPost > endPost)
		return;
	
	int rootValue = post[endPost];
	printf("%d ", rootValue);
	
    int i = startInorder;
    while(i <= endInorder && in[i] != rootValue) i++;
    
    int leftLength = i - startInorder;
    pre(startPost,startPost + leftLength-1,startInorder,i-1);
    pre(startPost+leftLength,endPost-1,i+1,endInorder);
}

int main() {
    pre(0,5,0,5);
    return 0;
}

运行结果如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值