重建二叉树

题目:  已知二叉树    前序遍历 {1, 2, 4, 7, 3, 5, 6, 8}     中序遍历{4, 7, 2, 1, 5, 3, 6, 8};

              重建二叉树。

              树结点结构

             typedef struct Node
            {
                    int value;
                    struct Node *pLeft;
                    struct Node *pRight;
           }Node;

思路:  前序遍历第一个结点一定为子树的根结点, 通过判断该结点在中序遍历中的位置来判断子树的左子树有几个结点,右子树有几个结点

              比如:  前序遍历中的1为树的跟结点,找到1在中序遍历中的位置,可判断出根结点为1的树中,左子树有三个结点值(2  4  7),右子树有四个结点值(3  5  6  8)

              对左子树与右子树分别进行递归运算

代码:


#include <iostream>
using namespace std;

#define M 8

typedef struct Node
{
    int value;
    struct Node *pLeft;
    struct Node *pRight;
}Node;

Node * BuildTree(int *pre, int *mid, int len)
{
    if (len == 0) // 表示无左子树或右子树了
    {
        return NULL;
    }
    int root = pre[0];
    int i = 0; //判断左子树有几个结点    右子树有len-i-1个节点
    while (pre[0] != mid[i])
    {
        i++;
    }
    
    Node *pNode = new Node;
    pNode->value = root;
    pNode->pLeft = BuildTree(pre+1, mid, i);
    pNode->pRight = BuildTree(pre+i+1, mid+i+1, len-i-1);
    return pNode;
}
void PrintfOut(Node *pHead)//后序遍历
{
    if (pHead == NULL)
        return;
    else
    {
        
        PrintfOut(pHead->pLeft);
        PrintfOut(pHead->pRight);
        cout << pHead->value << " ";
    }
}
int main()
{
    int pre[M] = {1, 2, 4, 7, 3, 5, 6, 8};
    int mid[M] = {4, 7, 2, 1, 5, 3, 6, 8};
    Node *pHead = NULL;
    pHead = BuildTree(pre, mid, M);
    PrintfOut(pHead);
    system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值