二叉搜索树的创建和遍历

二叉搜索树的创建的遍历

by:kvew     www.smatrix.org/bbs  http://blog.csdn.net/kvew/

 

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

typedef struct BST* tree_pointer;  //定义数据类型
typedef struct BST{
 int key;
 tree_pointer left;         
 tree_pointer right;
}BST;

tree_pointer CreateBST(tree_pointer root, int data){  // 创建一个根
 root = (tree_pointer)malloc(sizeof(BST));
 root->key = data;
 root->left = NULL;
 root->right = NULL;
 
    return root;
}

tree_pointer InsertBST(tree_pointer root, int data){  //  元素插入函数
 tree_pointer ptr,temp;
 ptr = root;

 if(ptr->key == data){      // 判断是否和当前结点的key相同
  printf("This data is aready in this tree!/n"); //相同则提示,并退出程序
  exit(1);
 }

 if(data < ptr->key){            // 如果比当前结点的key小,放到左子树上
  if(ptr->left == NULL){        //  若左子树为空,那么将其插到左子树上
   temp = (tree_pointer)malloc(sizeof(BST));
   temp->key = data;
   temp->left = NULL;
   temp->right = NULL;
   ptr->left = temp;
   return root;
  
  }
  else{                             //不为空,则继续向下查找
   ptr = ptr->left;
   InsertBST(ptr,data);      //递归调用
   return root;              //此处记得返回root
  }
 
 }
 else{                             //如果比当前结点key大,放到右子树上
  if(ptr->right == NULL){        
   temp = (tree_pointer)malloc(sizeof(BST)); //当前右子树为空则插入
   temp->key = data;
   temp->left = NULL;
   temp->right = NULL;
   ptr->right = temp;
   return root;
  }
  else{                        //不为空,则继续向下查找
   ptr = ptr->right;
   InsertBST(ptr,data);     //递归调用
   return root;              //记得此处返回root
  }

 }
 return NULL;
}

void preorder(tree_pointer ptr){ //前序遍历
  if(ptr){
   printf("%d ",ptr->key);
   preorder(ptr->left);
   preorder(ptr->right);
  }
}

void postorder(tree_pointer ptr){ //后序遍历
  if(ptr){
   postorder(ptr->left);
   postorder(ptr->right);
   printf("%d ",ptr->key);
  }
}


void inorder(tree_pointer ptr){ //中序遍历,对于BST,也就是从小到大打印出来了
  if(ptr){
   inorder(ptr->left);
   printf("%d ",ptr->key);
   inorder(ptr->right);
  
  }
}

int main(){
 int data = 0;
 tree_pointer root;
 
 root = NULL;


 printf("Please input a number to root:/n");
 scanf("%d",&data);
 
 root = CreateBST(root,data);

 printf("Now you can input others:/n");
 scanf("%d",&data);
 while(data != -1){
  root = InsertBST(root,data);
  scanf("%d",&data);
 }

 preorder(root);
 printf("/n");
 postorder(root);
 printf("/n");
 inorder(root);
 printf("/n");
 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值