根据二叉树的前序遍历序列和中序遍历序列求二叉树的后序遍历序列

手工模拟过程:

1.由先序遍历序列知该序列的第一个元素为树根;

2.在中序遍历序列中找到根元素,则其左边为树根的左子树,其右边为树根的右子树;

3.在树根的左子树中进行步骤1和步骤2的分析;

4.在树根的右子树中进行步骤1和步骤2的分析。

显然这是一个递归处理的过程。具体实现如下:


#include <stdio.h>

void LastSearchOrder(char *pr,char *in,int length) {
    if(!length) return ;
    int RootPos = 0;
    for(;RootPos<length;RootPos++) {
        if(in[RootPos] == *pr) break;
    }
    LastSearchOrder(pr+1,in,RootPos);
    LastSearchOrder(pr+1+RootPos,in+1+RootPos,length-RootPos-1);
    printf("%c",*pr);
}

int main()
{
    char* pr = "ABDECFG";
    char* in = "DBEAFCG";
    LastSearchOrder(pr,in,7);
    return 0;
}

根据二叉树的前序遍历序列和中序遍历序列建树实现:

#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {
    char elem;
    struct TreeNode * left;
    struct TreeNode * right;
}Node;

TreeNode* BuildTree(char *pr,char *in,int length) {
    if(!length) return NULL ;
    TreeNode * node = (TreeNode *)malloc(sizeof(TreeNode));
    node->elem = *pr;
    int RootPos = 0;
    for(;RootPos<length;RootPos++) {
        if(in[RootPos] == *pr) break;
    }
    node->left = BuildTree(pr+1,in,RootPos);
    node->right = BuildTree(pr+1+RootPos,in+1+RootPos,length-RootPos-1);
    printf("%c",*pr);
    return node;
}

int main()
{
    char* pr = "ABDECFG";
    char* in = "DBEAFCG";
    TreeNode * head = BuildTree(pr,in,7);
    return 0;
}



参考:http://blog.csdn.net/feliciafay/article/details/6816871



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设二叉树前序遍历序列为preorder,中序遍历序列为inorder,后序遍历序列为postorder。 我们可以通过递归的方式来构建二叉树,并得到后序遍历序列。具体步骤如下: 1. 从前序遍历序列中取出第一个元素,即为根节点。将其在中序遍历序列中的位置找到,左侧为左子树的中序遍历序列,右侧为右子树的中序遍历序列。 2. 根据左子树的中序遍历序列长度,在前序遍历序列中找到左子树的前序遍历序列,右侧为右子树的前序遍历序列。 3. 递归地构建左子树和右子树,得到左子树的后序遍历序列和右子树的后序遍历序列。 4. 将左子树的后序遍历序列和右子树的后序遍历序列拼接起来,再将根节点加入到末尾,得到整个二叉树后序遍历序列。 下面是Python代码实现: ```python def build_tree(preorder, inorder): if not preorder: # 如果前序遍历序列为空,返回空节点 return None root_val = preorder[0] # 取出根节点的值 root = TreeNode(root_val) # 在中序遍历序列中找到根节点的位置 idx = inorder.index(root_val) # 递归构建左子树和右子树 left_tree = build_tree(preorder[1:idx+1], inorder[:idx]) right_tree = build_tree(preorder[idx+1:], inorder[idx+1:]) # 拼接左子树、右子树和根节点的后序遍历序列 postorder = left_tree.postorder() + right_tree.postorder() + [root_val] return root ``` 其中,TreeNode是二叉树节点的类,postorder方法返回该节点为根的子树的后序遍历序列
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值