二叉树的基本操作--1

/*
*二叉树基本操作 范例
*/


//需要的头文件
#include <stdio.h>
#include <stdlib.h>


//节点的结构类型
typedef struct BiNode{
   int data;
   struct BiNode * Lchild;//左孩子
   struct BiNode * Rchild;//右孩子
}BiNode,*BiTree;


/*创建一个空的二叉树
*创建成功返回节点指针,否则返回空
*/
int init(BiTree &T){
    if(T=(BiNode *)malloc(sizeof(BiNode))){
    T->Lchild=NULL;
    T->Rchild=NULL;
    return 1;
   }else{
   return 0;
   }
}

/*
*销毁二叉树
*/

void Destory(BiTree &T){
   if(T){
     Destory(T->Lchild);
     Destory(T->Rchild);
     free(T);
     T=NULL;
   }
}
/*删除某节点左子树,已知二叉树及节点pt*/
void DeleteL(BiTree &T,BiTree pt){
   if(pt==NULL||pt->Lchild==NULL)
     return;
   Destory(pt->Lchild);
   pt->Lchild=NULL;
}
/*删除某节点右子树,已知二叉树及节点pt*/
void DeleteR(BiTree &T,BiTree pt){
   if(pt==NULL||pt->Lchild==NULL)
     return;
   Destory(pt->Rchild);
   pt->Lchild=NULL;
}

void InsertL(BiTree &T,int e,BiTree pt){
  BiTree p;
  //该节点存在的情况下
  if(pt){
    if(p=(BiNode *)malloc(sizeof(BiNode))){
        p->data=e;
        p->Lchild=pt->Lchild;
        p->Rchild=pt->Rchild;
        pt->Lchild=p;//最后把将pt的左孩子变成p
    }
  }
}

void InsertR(BiTree &T,int e,BiTree pt){
  BiTree p;
  //该节点存在的情况下
  if(pt){
    if(p=(BiNode *)malloc(sizeof(BiNode))){
        p->data=e;
        p->Lchild=pt->Lchild;
        p->Rchild=pt->Rchild;
        pt->Rchild=p;//最后把将pt的右孩子变成p
    }
  }
}

/*
*二叉树遍历
*先序,中序,后序
*/
//先序
void Preorder(BiTree T){
   if(T){
    printf("%d",T->data);
    Preorder(T->Lchild);
    Preorder(T->Rchild);
   }
}
//中序
void Inorder(BiTree T){
  if(T){
    Inorder(T->Lchild);
    printf("%d",T->data);
    Inorder(T->Rchild);
  }
}
//后序
void Postorder(BiTree T){
   if(T){
    Postorder(T->Lchild);
    Postorder(T->Rchild);
    printf("%d",T->data);
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值