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

      

    我要坚持一年,一年后的成功才是我想要的。
  • 相关阅读:
    查找父/子控件(元素、节点)
    【转载】单点系统架构的可用性与性能优化
    【转载】互联网架构,如何进行容量设计?
    【转载】细聊分布式ID生成方法
    【转载】秒杀系统架构优化思路
    【转载】程序员这口饭-职业规划解决方案
    【转载】一位软件工程师的6年总结
    【转载】VS工具使用——代码生成函数关系图
    【转载】VS工具使用——代码图
    【转载】一些VS2013的使用技巧
  • 原文地址:https://www.cnblogs.com/tianxia2s/p/6060916.html
Copyright © 2011-2022 走看看