关于二叉树的问题1-已知前序,中序求后序遍历

对于一棵二叉树而言,可以由其前序和中序或者中序和后序的遍历序列,确定一棵二叉树。

那么对于已知前序和中序序列,求后序序列也就是先还原二叉树,然后对其进行后序遍历即可。

二叉树结点的结构定义如下:

struct TreeNode
{
    char value;
    TreeNode *leftChild;
    TreeNode *rightChild;
};

实现代码如下:

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

TreeNode* allocateNode()
{

    TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
    node->leftChild = nullptr;
    node->rightChild = nullptr;
    return node;
}

char preStr[50], inStr[50];
void postOrder(TreeNode *T)
{
    if (T->leftChild != nullptr)
    {
        postOrder(T->leftChild);
    }
    if (T->rightChild != nullptr)
    {
        postOrder(T->rightChild);
    }
    printf("%c ", T->value);
}

TreeNode* builtTree(int start1, int end1, int start2, int end2)
{
    TreeNode *node = allocateNode();
    node->value = preStr[start1];
    int nodeIndex;
    for (int i = start2; i <= end2; ++i)
    if (preStr[start1] == inStr[i])
    {
        nodeIndex = i;
        break;
    }
    if (nodeIndex != start2)
    {
        node->leftChild = builtTree(start1 + 1, start1 + (nodeIndex - start2), start2, nodeIndex - 1);
    }

    if (nodeIndex != end2)
    {
        node->rightChild = builtTree(start1 + (nodeIndex - start2) + 1, end1, nodeIndex + 1, end2);
    }
    return node;
}

void main(void)
{
    scanf("%s",preStr);
    scanf("%s", inStr);
    int preLen = strlen(preStr);
    int inLen = strlen(inStr);
    TreeNode *root = builtTree(0, preLen - 1, 0, inLen - 1);
    postOrder(root);

}

 

posted on 2015-11-16 20:32  RunningSnail 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tgycoder/p/4969966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值