c语言数据结构之二叉(查找)树

本文详细介绍了如何使用C语言初始化二叉搜索树(BST),包括输入树节点、初始化过程、查找插入节点、遍历树节点等基本操作,并通过代码实例展示了这些操作的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.ertree.h

#ifndef _TREE_H
#define _TREE_H
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>

typedef struct node
{
char ch;
struct node *left,*right;
}TREE;
TREE* initTREE();
void printBeforeTREE(TREE* tree);
void printMidTREE(TREE* tree);
TREE* insertfindTREE(TREE* tree,char cha);
void printTREE(TREE* tree);
#endif;


2.ertree.c

#include "tree.h"
#include "stack.h"
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>

TREE* inputTREE(TREE* tree)
{
    if(tree==NULL)
    tree=(TREE*)malloc(sizeof(TREE));
    char ch;
    ch=getche();


    TREE* tree=NULL;

    if(ch=='#')
            return NULL;    

        tree->ch=ch;

return tree;
}
TREE* initTREE()
{

    TREE* tree=NULL;
    char ch;
ch=getche();
    if(ch=='#')
            return NULL;    
         tree=(TREE*)malloc(sizeof(TREE));
        tree->ch=ch;
    tree->left=initTREE();
        
    tree->right=initTREE();
return tree;
}
//查找插入 BST

TREE* insertfindTREE(TREE* tree,char cha){
if(tree==NULL)
{ tree=(TREE*)malloc(sizeof(TREE));
tree->left=tree->right=NULL;
tree->ch=cha;
}else if(tree->ch<cha)
{
    tree->right=insertfindTREE(tree->right,cha);

}else
{
    tree->left=insertfindTREE(tree->left,cha);
}

return tree;

}


void printTREE(TREE* tree)
{

    
    if(tree!=NULL)
    {

    printTREE(tree->left);
    
    printTREE(tree->right);
    printf("%c\t",tree->ch);
    }
}
void printBeforeTREE(TREE* tree)
{

    
    if(tree==NULL)
        return ;
    printf("%c\t",tree->ch);
    printBeforeTREE(tree->left);
    printBeforeTREE(tree->right);
}
void printMidTREE(TREE* tree)
{
    TREE *p=tree;
STACK * sta =initSTACK();
 push(sta,&tree);

    
    while(!isEmpty(sta))
    {
    

        while(p)
        {
            p=p->left;
        push(sta,&p);
    
        }
        pop(sta,&p);
        if(!isEmpty(sta))
        {
            pop(sta,&p);
            printf("%c\t",p->ch);
        p=p->right;
        push(sta,&p);
        }

    }


3.main.c


//typedef  int ElementType;
//#define    ElementType TREE ;
#include "tree.h"
#include "stack.h"
int main()
{
TREE *tree=initTREE();
 printTREE(tree);
    /*int a;
    STACK* sta=initSTACK();
    a=2;
    push(sta,&a);
    a=3;
        push(sta,&a);
        a=4;
            push(sta,&a);
            while(!isEmpty(sta))
            {pop(sta,&a);
            printf("%d\n",a);
            }
    */        

 
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值