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

      

    我要坚持一年,一年后的成功才是我想要的。
  • 相关阅读:
    Java求区间连续最大和的三种解法(含输出起始位置)
    Java批量操作和遍历文件程序收集
    FastJson序列化部分字段的方法
    Spring源码之一步步拓展实现spring-mybatis
    Spring源码之BeanFactoryPostProcessor的执行顺序
    Classpath entry points to a non-existent location:D:libjavajdk8jrelibextaccess-bridge-32.jar
    编译Spring源码省心小贴士
    (转)HttpServletResquest对象
    (转)ServletConfig与ServletContext
    Oracle复习(复习精简版v1.0)
  • 原文地址:https://www.cnblogs.com/tianxia2s/p/6060916.html
Copyright © 2011-2022 走看看