c语言实现:二叉树的建立与递归调用

typedef struct Node{       //结构体类型
 int data;
 struct Node *leftchild;
 struct Node *rightchild;
}Node;      

//--------------------------------------------------------   初始化    -----------------------------------------------------------------------//                   

void InitBinaryTree(Node**root,int elem){      //初始化
    *root=(Node*)malloc(sizeof(Node));
    if(!(*root)){
    printf("Memory allocation for root failed.\n");
    return;
    }
    (*root)->data=elem;
    (*root)->leftchild=NULL;
    (*root)->rightchild=NULL;
}

//------------------   插入结点,若插入数据小于父结点,插入左子树;若大于父结点,插入右子树  ---------------//

void InsertNode(Node *root,int elem){
    Node *newnode=NULL;
    Node *p=root,*last_p=NULL;
    newnode=(Node*)malloc(sizeof(Node));
    if(!newnode){
        printf("Memory allocation for newnode failed.\n");
        return;
    }
    newnode->data=elem;
    newnode->leftchild=NULL;
    newnode->rightchild=NULL;
    while(NULL!=p){       //循环让头指针指向它要插入结点的位置
        last_p=p;
        if(newnode->data < p->data){
            p=p->leftchild;
        }
        else if(newnode->data > p->data){
            p=p->rightchild;
        }
        else{
            printf("Node to be inserted has existed.\n");
            free(newnode);
        return;
        }
    }
    p=last_p;
    if(newnode->data < p->data){
        p->leftchild=newnode;
    }
    else{
        p->rightchild=newnode;
    }
}

//----------------------------------------------打印结点-------------------------------------------//

void visit(Node *p){
    printf("%d\n",p->data);
}

//--------------------------------递归的前序、中序、后序遍历-------------------------------//

void MidTreverse(Node *root){
    if(root != NULL){
        MidTreverse(root->leftchild);
        visit(root);
        MidTreverse(root->rightchild);
    }
}

 

void PreTreverse(Node *root){
    if(root != NULL){
        visit(root);
        PreTreverse(root->leftchild);
        PreTreverse(root->rightchild);
    }
}

void BeTreverse(Node *p){
    if(p!=NULL){
        BeTreverse(p->leftchild);
        BeTreverse(p->rightchild);
        visit(p);
    }
}

//---------------------------------------------------主函数--------------------------------------//

int main(){
    Node *head=NULL;
    InitBinaryTree(&head, 4);
    InsertNode(head, 2);
    InsertNode(head, 1);
    InsertNode(head, 3);
    InsertNode(head, 6);
    InsertNode(head, 5);
    InsertNode(head, 7);
//    MidTreverse(head);
    PreTreverse(head);
//    BeTreverse(head);
    printf("Hello world!\n");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值