通过输入字符串来构建二叉树

对二叉树的一系列操作都是建立在先将二叉树构造出来的前提上。大四考研的某天早上偷偷躲在宿舍敲二叉树的代码,也是醉醉的。学习就应该趁年轻,老了就学不动了。

首先是对二叉树的节点的一个声明:

typedef struct BTree{
    char str;
    struct BTree * lchild;
    struct BTree * rchild;
}BTree;

  然后我是打算用递归外加先序的方式对二叉树进行构建的,也就对输入字符串提出一个要求:

printf("Please input the tree(use char and #)\n要求按照先序遍历的方式输入,加上#进行区分\n例如123# #4##5##:\n");

构建二叉树的函数:

BTree* creat_tree(){
    BTree* temp;
    while(*p==' ')p++;
    if(*p=='#'){
        p++;
        return NULL;
    }
    if(*p!=' '){
        temp = (BTree *)malloc(sizeof(BTree));
        temp->str=*p++;
        temp->lchild=creat_tree();
        temp->rchild=creat_tree();
    }
    return temp;
}

  同时为了将头结点单独获取保存,供后边操作使用,因此将头结点的构建单独放在main函数中处理了一下,下边是我的完整代码,运行无误。

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

#define MAX 100

char * p;
typedef struct BTree{
    char str;
    struct BTree * lchild;
    struct BTree * rchild;
}BTree;

BTree* creat_tree(){
    BTree* temp;
    while(*p==' ')p++;
    if(*p=='#'){
        p++;
        return NULL;
    }
    if(*p!=' '){
        temp = (BTree *)malloc(sizeof(BTree));
        temp->str=*p++;
        temp->lchild=creat_tree();
        temp->rchild=creat_tree();
    }
    return temp;
}

void pre_visit(BTree* node){
    printf("%c",node->str);
    if(node->lchild!=NULL)pre_visit(node->lchild);
    if(node->rchild!=NULL)pre_visit(node->rchild);
}
int main()
{
    char tree[MAX];p=tree;
    BTree * head;
    printf("Please input the tree(use char and #)\n要求按照先序遍历的方式输入,加上#进行区分\n例如123# #4##5##:\n");
    //scanf("%s",tree);
    gets(tree);

    if(*p!='\0'&&*p!=' '&&*p!='#'){
        head=(BTree *)malloc(sizeof(BTree));
        head->str=*p++;
        //printf("head is %c",head->str);
        head->lchild=creat_tree();
        head->rchild=creat_tree();
    }

    printf("tree is :\n");
    pre_visit(head);
    return 0;
}

  

转载于:https://www.cnblogs.com/tianxia2s/p/6060916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值