二叉树遍历方式的转化(递归写法)

大家都知道二叉树已知中序遍历和后序遍历可以求前序遍历

已知前序遍历和中序遍历可以求后序遍历,那么现在实现一下


想法基本是利用递归,先找到根节点的位置,然后利用左右子树递归

前序遍历+中序遍历 求 后序遍历:

void dfs(char *inorder,char *preorder,int len){
	if(len == 0) return ;
	int rootindex = 0;
	while(rootindex<len){
		if(inorder[rootindex] == preorder[1])
			break;
		rootindex++;
	}
	dfs(inorder,preorder+1,rootindex);
	dfs(inorder+rootindex+1,preorder+rootindex+1,len-1-rootindex);
	printf("%c\n",*inorder );
}



中序遍历+后序遍历-->先序遍历

void dfs(char *inorder,char*preorder,int len){
	if(len == 0) return ;
	int rootindex = 0;
	printf("%c\n",postorder[len-1]);
	while(rootindex<len){
		if(inorder[rootindex]==postorder[len-1])
			break;
		rootindex++;
	}
	dfs(inorder,postorder,rootindex);
	dfs(inorder+rootindex+1,postorder+rootindex,len-1-rootindex);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值