Data Structure --- binary sorttree in C Language)
This is also called the binary search tree.
Code:
// Binary Search Tree // Yang Xin # include
# Include
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; // search failed} int main () {BSTree T; int tag = 1; int m, n; printf (build a binary sorting tree, enter the sequence ending with-1:; CreateBST (& T); printf (middle-order binary tree traversal; sequence: :); InOrder (T); printf (); while (tag! = 0) {printf (enter the element you want to search for :); scanf (% d, & n); if (SearchBST (T, n) = NULL) printf (Sorry, an error occurred while searching !); Elseprintf (search successful! The number to be searched is % d, SearchBST (T, n)-> key); printf (whether to continue searching is: Press 1 otherwise press 0 :); scanf (% d, & tag);} return 0 ;}
Result: