人生列车

follow on!success!

导航

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

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

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

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;
}

  

posted on 2016-11-14 10:28  tianxia2s  阅读(6885)  评论(0编辑  收藏  举报