通過輸入字符串來構建二叉樹


對二叉樹的一系列操作都是建立在先將二叉樹構造出來的前提上。大四考研的某天早上偷偷躲在宿舍敲二叉樹的代碼,也是醉醉的。學習就應該趁年輕,老了就學不動了。

首先是對二叉樹的節點的一個聲明:

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM