tree.h

#ifndef _TREE_H
#define _TREE_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int data_type;

//创建一个树节点
typedef struct treenode
{
    struct treenode *lNode;
    data_type data;
    struct treenode *rNode;
    
}treeNode;

enum VALUE
{
    ERROR = -1,
    OK
};

//给节点分配空间
treeNode *create_tree(data_type Data);

//插入节点
int insert_tree(treeNode *pTree,data_type Data);

//先序遍历
int PreOrder(treeNode *pTree);

//中序遍历
int MidOrder(treeNode *pTree);

//后序遍历
int PostOrder(treeNode *pTree);

//销毁
int destroy_tree(treeNode *pTree);



#endif

 

tree.c

#include "../include/tree.h"



//给节点分配空间
treeNode *create_tree(data_type Data)
{
    treeNode *pTree = NULL;
    pTree = (treeNode *)malloc(sizeof(treeNode));
    if(NULL == pTree)
    {
        printf("malloc error");
        return NULL;
    }
    memset(pTree,0,sizeof(treeNode));
    pTree->data = Data;
    return pTree;
}

//插入节点
int insert_tree(treeNode *pTree,data_type Data)
{
    if(NULL == pTree)
    {
        return ERROR;
    }
    
    treeNode *pNew = NULL;
    pNew = (treeNode *)malloc(sizeof(treeNode));
    if(NULL == pNew)
    {
        printf("malloc error");
        return ERROR;
    }
    memset(pNew,0,sizeof(treeNode));
    pNew->data = Data;
    
    while(1)
    {    
        if(pTree->data >= pNew->data)
        {
            if(NULL != pTree->lNode)
            {
                pTree = pTree->lNode;
            }
            else
            {
                pTree->lNode = pNew;
                break;
            }
        }
        else
        {
            if(NULL != pTree->rNode)
            {
                pTree = pTree->rNode;
            }
            else
            {
                pTree->rNode = pNew;
                break;
            }
        }
    }
    return OK;

}

//先序遍历//根左右
int PreOrder(treeNode *pTree)
{
    if(NULL == pTree)
    {
        return ERROR;
    }
    printf("%d ",pTree->data);
    PreOrder(pTree->lNode);
    PreOrder(pTree->rNode);
}

//中序遍历//左根右
int MidOrder(treeNode *pTree)
{
    if(NULL == pTree)
    {
        return ERROR;
    }
    MidOrder(pTree->lNode);
    printf("%d ",pTree->data);
    MidOrder(pTree->rNode);
}

//后序遍历//左右根
int PostOrder(treeNode *pTree)
{
    if(NULL == pTree)
    {
        return ERROR;
    }
    PostOrder(pTree->lNode);
    PostOrder(pTree->rNode);
    printf("%d ",pTree->data);
}

//销毁
int destroy_tree(treeNode *pTree)
{
    if(NULL == pTree)
    {
        return ERROR;
    }
    //销毁的思想:递归
    //先销毁左子树
    destroy_tree(pTree->lNode);
    //再销毁右子树
    destroy_tree(pTree->rNode);
    //最后:销毁树根
    free(pTree);
    pTree = NULL;
}

 

main.c

 

posted @ 2022-05-25 14:36  西北小蚂蚁  阅读(19)  评论(0编辑  收藏  举报