zoukankan      html  css  js  c++  java
  • 数据结构 树的创建(井号法)

    //树的创建--井号法创建树
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    typedef struct _TreeNode{
        char data;
        struct _TreeNode * leftchild;
        struct _TreeNode * rightchild;
    }TreeNode, *TreeNodePointer;
    
    /*
    单纯的先序遍历结果,中序遍历结果,后序遍历结果都无法还原一棵二叉树,
    必须用中序结果+先序结果---或者中序结果+后序结果  两两结合才能还原一棵树
    
    井号法创建树思想:
    将一个树所有的结点都补成二叉,没有节点的地方用#代替,用先序遍历的结果还原一棵二叉树
    
    */
    
    //创建树
    TreeNodePointer CreateTree(){
        char ch = 0;
        printf("请输入该结点的数据
    ");
        scanf("%c", &ch);
        getchar();
        if (ch == '#')
        {
            return NULL;
        }
        //创建根节点
        TreeNodePointer root = (TreeNodePointer)malloc(sizeof(TreeNode));
        //初始化
        memset(root, 0, sizeof(TreeNode));
        //结点赋值
        root->data = ch;
        root->leftchild = CreateTree();
        root->rightchild = CreateTree();
        return root;
    }
    
    //销毁树--后序遍历销毁(结点删除了怎么找左子树,右子树啊)
    void DestroyTree(TreeNodePointer *root){
        if (root == NULL)
        {
            printf("传入参数不可以为空!
    ");
            return;
        }
        TreeNodePointer temp = *root;
        //销毁左子树
        if (temp->leftchild!=NULL)
        {
            DestroyTree(&temp->leftchild);
        }
        //销毁右子树
        if (temp->rightchild!=NULL)
        {
            DestroyTree(&temp->rightchild);
        }
        //销毁根结点
        free(temp);
        temp = NULL;
        *root = NULL;
    }
    
    //中序遍历树
    void Inoder(TreeNodePointer root){
        if (root==NULL)
        {
            printf("传入参数不可以空!
    ");
            return;
        }
        //遍历左子树
        if (root->leftchild!=NULL)
        {
            Inoder(root->leftchild);
        }
        
        //遍历根结点
        printf("%c", root->data);
        //遍历右子树
        if (root->rightchild != NULL)
        {
            Inoder(root->rightchild);
        }
    }
    
    void main(){
        //创建树
        TreeNodePointer root=CreateTree();
        //遍历树
        Inoder(root);
        //销毁树
        DestroyTree(&root);
        system("pause");
    }

  • 相关阅读:
    几种php加速器比较
    细说firewalld和iptables
    Linux上iptables防火墙的基本应用教程
    mysql 字符串按照数字类型排序
    《设计模式之禅》之六大设计原则下篇
    《设计模式之禅》之六大设计原则中篇
    《设计模式之禅》之六大设计原则上篇
    git bash 乱码问题之解决方案
    nexus没有授权导致的错误
    Java之微信公众号开发
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5732114.html
Copyright © 2011-2022 走看看