二叉树学习-已知中序、后序,求先序

本文介绍了一种利用中序和后序遍历序列来确定二叉树先序遍历序列的方法,并通过代码实例详细解释了实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历

Input

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。 

Output

 输出二叉树的先序遍历序列

Sample Input

2
dbgeafc
dgebfca
lnixu
linux

Sample Output

abdegcf
xnliu
代码如下:
#include <iostream>
#include"cstdio"
#include"cstring"
#include"cstdlib"
using namespace std;
char ins[1050],pos[1050];
struct node
{
    char data;
    node *lch,*rch;
};
node *build(char *ins ,char*pos,int n)
{
    if(n<=0) return NULL;
    node *p;
    p=(node*)malloc(sizeof(node));
    p->data=pos[n-1];
    int k;
    for( k=0;k<n;k++)
        if(ins[k]==pos[n-1])
        break;
    p->lch=build(ins,pos,k);
    p->rch=build(ins+k+1,pos+k,n-k-1);
    return p;
}
void xianxu(node *p)
{
    if(p!=NULL)
    {
        printf("%c",p->data);
        xianxu(p->lch);
        xianxu(p->rch);
    }
}
int main()
{
     int t;
     scanf("%d",&t);
     while(t--)
     {memset(ins,'\0',sizeof(ins));
      memset(pos,'\0',sizeof(pos));
      scanf("%s%*c%s",ins,pos);
      node *tree;
      tree=(node*)malloc(sizeof(node));
      int n=strlen(ins);
      tree=build(ins,pos,n);
      xianxu(tree);
      putchar('\n');
     }
    return 0;
}
假设我们已知一棵二叉树遍历序列遍历序列,可以通过以下步骤来出它的后序遍历序列: 1. 在序列中,第一个元素为根节点。 2. 在中序列中,找到根节点的位置,根节点左侧的部分为左子树的中遍历序列,右侧的部分为右子树的中遍历序列。 3. 根据左子树的中遍历序列的长度,可以在遍历序列中确定左子树的遍历序列右子树的遍历序列。 4. 递归地对左子树右子树重复以上步骤,直到子树为空或只有一个节点。 5. 最后将根节点加入后序遍历序列中,即可得到二叉树后序遍历序列。 下面是一个 Python 代码示例: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root = TreeNode(root_val) idx = inorder.index(root_val) left_inorder = inorder[:idx] right_inorder = inorder[idx+1:] left_preorder = preorder[1:1+len(left_inorder)] right_preorder = preorder[1+len(left_inorder):] root.left = buildTree(left_preorder, left_inorder) root.right = buildTree(right_preorder, right_inorder) return root def postorderTraversal(root): if not root: return [] res = [] res.extend(postorderTraversal(root.left)) res.extend(postorderTraversal(root.right)) res.append(root.val) return res preorder = [1, 2, 4, 5, 3, 6, 7] inorder = [4, 2, 5, 1, 6, 3, 7] root = buildTree(preorder, inorder) postorder = postorderTraversal(root) print(postorder) # 输出 [4, 5, 2, 6, 7, 3, 1] ``` 以上代码中,`buildTree` 函数接收遍历序列遍历序列作为参数,返回构建出的二叉树的根节点。`postorderTraversal` 函数接收根节点作为参数,返回后序遍历序列。在 `buildTree` 函数中,我们根据序列中的第一个元素构建出根节点,然后在中序列中找到根节点的位置,根据位置将中序列分为左右两部分,递归地构建出左右子树。在 `postorderTraversal` 函数中,我们递归遍历左子树右子树,然后将根节点的值加入到后序序列中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值