二叉树的建立和先中后顺序遍历

二叉树的建立

二叉树建立问题

个人观点
二叉树是一对多的关系,所以在存储结构中借助链表节点进行动态存储。首先建立节点,递归进行建立。

typedef char ElemType;
typedef struct node
{
    ElemType data;
    struct node *lchild;
    struct node *rchild;
}*BiTree, BiNode;
char str[29];
int i;
BiTree CreatTree()
{
    if(str[i]==',')
    {
        i++;
        return 0;
    }
    else
    {
        BiTree T=(BiTree)malloc(sizeof(BiNode));
        T->data=str[i];
        i++;
        T->lchild=CreatTree();
        T->rchild=CreatTree();
        return T;
    }
    return 0;
}

先中后序便利

个人观点
在二叉树的节点中,有左右子树和根节点的缘故,分为先序遍历,中序遍历和后序遍历,递归访问每一个节点。

int TreeFront(BiTree root)
{
    if(root!=NULL)
    {
        printf("%c", root->data);
        TreeFront(root->lchild);
        TreeFront(root->rchild);
    }
    return 0;
}

指针越界的问题
在linux系统的系统版本ubuntu上,存在指针越界问题

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct node
{
    ElemType data;
    struct node *lchild;
    struct node *rchild;
}*BiTree, BiNode;
char str[29];
int i;
BiTree CreatTree()
{
    if(str[i]==',')
    {
        i++;
        return 0;
    }
    else
    {
        BiTree T=(BiTree)malloc(sizeof(BiNode));
        T->data=str[i];
        i++;
        T->lchild=CreatTree();
        T->rchild=CreatTree();
        return T;
    }
    return 0;
}
int TreeMod(BiTree root)
{
    if(root!=NULL)
    {
        TreeMod(root->lchild);
        printf("%c", root->data);
        TreeMod(root->rchild);
    }
    return 0;
}

int TreeFront(BiTree root)
{
    if(root!=NULL)
    {
        printf("%c", root->data);
        TreeFront(root->lchild);
        TreeFront(root->rchild);
    }
    return 0;
}

int TreeRear(BiTree root)
{
    if(root!=NULL)
    {
        TreeRear(root->lchild);
        TreeRear(root->rchild);
        printf("%c", root->data);
    }
    return 0;
}
int main()
{
    int n;
    scanf("%d", &n);
    for(int j=0; j<n; j++)
    {
        scanf("%s", str);
        BiTree root;
        i=0;
        root=CreatTree();
        TreeMod(root);
        printf("\n");
        TreeRear(root);
        printf("\n");
        TreeFront(root);
        printf("\n");
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值