zoukankan      html  css  js  c++  java
  • 通过输入字符串来构建二叉树

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

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

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

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

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

    构建二叉树的函数:

    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 #)
    要求按照先序遍历的方式输入,加上#进行区分
    例如123# #4##5##:
    ");
        //scanf("%s",tree);
        gets(tree);
    
        if(*p!=''&&*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 :
    ");
        pre_visit(head);
        return 0;
    }
    

      

    我要坚持一年,一年后的成功才是我想要的。
  • 相关阅读:
    杨辉三角形
    open live writer
    已加载"C:WindowsSysWOW64msvcp120d.dll".无法查找或打开 PDB 文件.
    4.标准信号与槽
    python的单元测试unittest(一)
    python面向对象--类与对象
    python的文件操作与目录操作os模块
    Jenkins的安装与配置
    selenium切换到iframe
    selenium对富文本的操作
  • 原文地址:https://www.cnblogs.com/tianxia2s/p/6060916.html
Copyright © 2011-2022 走看看