Data Structure --- implement BinarySortTree in C language --- cbinarysorttree
This is also called the binary search tree.
Code:
// Binary Search Tree // Yang Xin # include <stdio. h> # include <stdlib. h> typedef struct node {int key; struct node * lchild, * rchild;} BSTNode, * BSTree; // insert int InsertBST (BSTree * bst, int k) {BSTree r, s, pre; r = (BSTree) malloc (sizeof (BSTNode); r-> key = k; r-> lchild = NULL; r-> rchild = NULL; if (* bst = NULL) {* bst = r; return 1;} pre = NULL; s = * bst; while (s) {if (k = s-> key) return 0; else if (k <s-> key) {pre = s; S = s-> lchild;} else {pre = s; s = s-> rchild;} if (k <pre-> key) pre-> lchild = r; elsepre-> rchild = r; return 1;} void CreateBST (BSTree * bst) {int key; * bst = NULL; scanf ("% d", & key ); while (key! =-1) {InsertBST (bst, key); scanf ("% d", & key) ;}/ ** print Binary Tree: * sequential traversal **/void InOrder (BSTree root) {if (root! = NULL) {InOrder (root-> lchild); printf ("% d", root-> key); InOrder (root-> rchild );}} /** search **/BSTree SearchBST (BSTree bst, int key) {BSTree q; q = bst; // recursive while (q) {if (q-> key = key) return q; if (q-> key) q = q-> lchild; elseq = q-> rchild ;} return NULL; // query Failed} int main () {BSTree T; int tag = 1; int m, n; printf ("Create a binary sorting tree, enter the sequence to end with-1: \ n "); CreateBST (& T); printf (" traversing the binary tree in ascending order; the sequence is \ n "); InOrder (T ); printf ("\ n"); while (tag! = 0) {printf ("Enter the element you want to search for: \ n"); scanf ("% d", & n); if (SearchBST (T, n) = NULL) printf ("sorry, an error occurred while searching! \ N "); elseprintf (" search successful! The number to be searched is % d \ n ", SearchBST (T, n)-> key); printf (" whether to continue searching is: Press 1; otherwise press 0: \ n "); scanf ("% d", & tag);} return 0 ;}
Result:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.