Linux c 二叉搜索树(节点创建、插入BST)


  1 /*
  2  * File: binary_search_tree.c
  3  * --------------------------
  4  * 2017年7月8日
  5  *
  6  */
  7 
  8 #include <stdio.h>
  9 #include <stdlib.h>
 10 
 11 struct node
 12 {
 13         int data;
 14         struct node *left;
 15         struct node *right;
 16 };
 17 
 18 struct node *createNode(int val);
 19 void insertNode(struct node **root, struct node* p);
 20 
 21 int main(int argc, char *argv)
 22 {
 23         struct node *head = NULL;
 24         int array[] = {3,6,7,2,8,5,4,9};
 25         int i;
 26         printf("****\n");
 27         for(i = 0; i < 1; i++)
 28         {
 29                 insertNode(&head, createNode(array[i]));
 30         }
 31         printf("*******\n");
 32         return 0;
 33 }
 34 
 35 //创建节点
 36 struct node *createNode(int val)
 37 {
 38         struct node *temp = NULL;
 39         temp = (struct node *)malloc(sizeof(struct node));
 40         temp->data = val;
 41         temp->left = NULL;
 42         temp->right = NULL;
 43         return temp;
 44 }
 45 
 46 //插入节点
 47 void insertNode(struct node **root, struct node* p)
 48 {
 49         struct node *temp = *root;
 50         if(temp == NULL)
 51         {
 52                 *root = p;
 53         }
 54         else
 55         {
 56                 if(p->data < temp->data)  //小于,则放至该节点的左子树
 57                         {
 58                                 insertNode(&(temp->left), p);  //递归
 59                         }
 60                 else if(p->data > temp->data)  //大于,则放至该节点的右子数
 61                         {
 62                                 insertNode(&(temp->right), p);  //递归
 63                         }
 64         }
 65 }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值