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

来源:互联网 发布:ubuntu rm rf 编辑:程序博客网 时间:2024/06/06 04:02
  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 }

原创粉丝点击