Data Structure --- binary sorttree in C Language)

Source: Internet
Author: User

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:

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.