二叉树先序遍历中序遍历结果得出该树,并以后序遍历形式输出

简单形式写下思想。仅供交流。有问题还望指正。

#include<iostream>

using namespace std;
struct BinaryTreeNode
{
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
//int beforeSequence[8] = {1, 2, 4, 7, 3, 5, 6, 8};
//int midSequence[8] = {4, 7, 2, 1, 5, 3, 8, 6};
int beforeSequence[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int midSequence[8] = {8, 4, 2, 5, 1, 6, 3, 7};
int nodeSize = 8;
int findFirstIndex(int starting, int ending) //以中序遍历数字串为依据。每次找到串中第一次在先序遍历中出现的元素。输出其在中序遍历串中的下标
{
    int i, j;
    for (i = 0; i < nodeSize; i++)
    {
        for (j = starting; j <= ending; j++)
        {
            if (beforeSequence[i] == midSequence[j])
                return j;
        }
    }
    return -1;
}
BinaryTreeNode* createBinaryTree(int starting, int ending)
{
    if (starting > ending)
        return NULL;
    else
    {
        BinaryTreeNode* bi = new BinaryTreeNode;
        int index = findFirstIndex(starting, ending); //先序遍历第一次出现的作为根节点
        if (index == -1)
        {
            cout<<"error";
            return NULL;
        }
        bi->value = midSequence[index];
        bi->left = createBinaryTree(starting, index - 1);
        bi->right = createBinaryTree(index + 1, ending);
        return bi;
    }
}
void printAfter(BinaryTreeNode* t)//结果以后序遍历的形式输出。简单测试正确。思想仅供交流
{
    if (t == NULL)
    {
         return;
    }
    else
    {
          printAfter(t->left);
        printAfter(t->right);
        cout<< t->value;
    }
}
int main()
{
    BinaryTreeNode* node = createBinaryTree(0, 7);
    printAfter(node);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值