UVa - 536 - Tree Recovery(给定中序和先序求后序,递归)



思路:由先序遍历可得到根节点。在中序遍历中找到根节点的位置,然后分别递归左子树和右子树,一般的思路到这里是递归建树,但是由于是要求后序遍历的序列。是左孩子+右孩子+根节点,而递归建树时是通过找到根节点,然后先递归左子树,然后递归右子树 ,所以直接输出的就是后序遍历的结果。

#include<iostream>
#include<cstring>
using namespace std;
char s1[30],s2[30]; //先序和中序 
void build(int p1,int p2,int q1,int q2){
	if(p1>p2)return ;
	int i=q1;
	while(s1[p1]!=s2[i])i++;
	
	build(p1+1,p1+i-q1,q1,i-1);//左
	 
	build(p1+1+i-q1,p2,i+1,q2);//右 
	
	cout<<s2[i];
	
}


int main(){
	while(cin>>s1>>s2){
		int len = strlen(s1)-1;
		build(0,len,0,len);
		puts("");
	}
	
	return 0;	
} 

递归过程中,有效输出是到p1>p2的前一个位置,先输出这个位置。由于是先进行的左子树的递归,一直到最后一个最小左子树(没有孩子结点),输出该结点,在这个递归中,有相应的右子树的递归,输出该结点,然后一步一步往上返回 ,输出的结点的顺序就是后序遍历。

以下是根据给定二叉树中序和先序遍历序列来二叉树的过程: 1. 首先,我们需要了解中序遍历和先序遍历的特点: - 中序遍历的顺序是左子树 -> 根节点 -> 右子树。 - 先序遍历的顺序是根节点 -> 左子树 -> 右子树。 2. 根据中序遍历和先序遍历的特点,我们可以得出以下结论: - 先序遍历的第一个节点是根节点。 - 在中序遍历中,根节点的左边是左子树的节点,根节点的右边是右子树的节点。 3. 根据以上结论,我们可以进行递归操作来构建二叉树: - 从先序遍历中取出第一个节点作为根节点。 - 在中序遍历中找到根节点的位置,将中序遍历分为左子树和右子树。 - 根据左子树和右子树的节点数量,从先序遍历中取出相应数量的节点作为左子树和右子树的先序遍历序列。 - 递归地构建左子树和右子树。 4. 递归的终止条件是中序遍历序列为空。 下面是一个示例代码,演示了如何根据给定中序遍历和先序遍历序列构建二叉树的过程: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def buildTree(inorder, preorder): if not inorder: return None root_val = preorder[0] root = TreeNode(root_val) root_index = inorder.index(root_val) left_inorder = inorder[:root_index] right_inorder = inorder[root_index+1:] left_preorder = preorder[1:1+len(left_inorder)] right_preorder = preorder[1+len(left_inorder):] root.left = buildTree(left_inorder, left_preorder) root.right = buildTree(right_inorder, right_preorder) return root # 示例输入 inorder = ['D', 'B', 'E', 'A', 'F', 'C'] preorder = ['A', 'B', 'D', 'E', 'C', 'F'] # 构建二叉树 root = buildTree(inorder, preorder) # 输出二叉树后序遍历序列 def postorderTraversal(root): if not root: return [] result = [] result += postorderTraversal(root.left) result += postorderTraversal(root.right) result.append(root.val) return result postorder = postorderTraversal(root) print("后序遍历序列:", postorder) # 输出:['D', 'E', 'B', 'F', 'C', 'A'] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值