【2018机试笔记】二叉树

王道机试例3.4


      不同与王道例题的写法,用考研时习惯的代码书写方法

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

using namespace std;


char pre[26];///前序遍历输入
char in[26];///中序遍历输入

typedef struct BiNode
{
    char data;
    struct BiNode *lchild,*rchild;

}BiNode,*BiTree;

BiNode *CreatBiTree(char pre[],char in[],int l1,int r1,int l2,int r2)
{
    ///用前序遍历和中序遍历创建一个二叉树,l1,r1为前序遍历数组头尾指针,l2,r2为后序遍历数组头尾指针
    if(l1>r1)
    {
        return NULL;
    }
    BiNode *s;
    int i;
    s=(BiTree)malloc(sizeof(BiNode));
    s->data=pre[l1];
    s->lchild=NULL;
    s->rchild=NULL;

    for(i=l2;in[i]!=pre[l1]&&i<=r2;i++)///i<=r2 取大于等于  i从l2开始(不必从0开始遍历 太慢了)
    {
        if(in[i]==pre[l1])
        {
            break;
        }
    }
    s->lchild=CreatBiTree(pre,in,l1+1,l1+i-l2,l2,i-1);
    s->rchild=CreatBiTree(pre,in,l1+i-l2+1,r1,i+1,r2);
    return s;
}

BiNode* CreatTree(char pre[],char in[],int n)
{
    int l1=0;
    int r1=n-1;
    int l2=0;
    int r2=n-1;

    return CreatBiTree(pre,in,l1,r1,l2,r2);

}

void post_order (BiTree T)
{
    if(T!=NULL)
    {
        post_order(T->lchild);
        post_order(T->rchild);
        printf("%c",T->data);
    }
}

int main()
{

    int n=0;///表示结点数
    BiTree T;
    scanf("%s",pre);
    scanf("%s",in);
    for(int i=0;pre[i]!=0;i++)
    {
        n++;
    }
    T=CreatTree(pre,in,n);
    post_order(T);
    printf("\n");

    return 0;
}


若要使用malloc函数 记得加入库stdlib.h

#include <stdlib.h>

在CreatBiTree()函数中
    s->lchild=CreatBiTree(pre,in,l1+1,l1+i-l2,l2,i-1);
    s->rchild=CreatBiTree(pre,in,l1+i-l2+1,r1,i+1,r2);
查找前序遍历的元素A时,A在中序遍历的相对位置j,即是前序遍历中左子树最后一个结点的位置。j+1则是前序遍历序列中第一个右子树结点的位置。

其中i即对应着这里的j ,那为什么函数的r1参数变化不用i而用l1+i-l2呢?

是因为i是中序遍历的下标,直接用i不是在前序序列中对应的位置。

i-l2是左子树的长度

l1+i-l2则是左子树的尾

l1+i-l1+1则是右子树的头



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值