First, define the storage structure of the binary tree
1 /* */2char treeelemtype; 3 struct Tagbitreenode {4 Treeelemtype data; // node Data 5 struct tagbitreenode *lchild, *rchild; // children's hands around the knot. 6 }bitrnode, *bitrnodeptr;
The lookup function of the binary sort tree is implemented as follows:
1 /*2 * * Recursive implementation of @brief binary sorting tree lookup3 * * @param4 * * @arg root: Root node5 * * @arg key: keywords to find6 * * @arg parent nodes of the Parent:root node, with an initial value of NULL7 * * @arg Result: Find the node pointer found in the results8 * * @retval If the lookup succeeds, the result points to the element node and returns 1;9 * * If it fails, the result points to the last node accessed on the lookup path. Ten */ One intBst_search (bitrnodeptr root, Treeelemtype key, bitrnodeptr parent, Bitrnodeptr *result) A { - if(Root = NULL) {//Find not successful -*result =parent; the return 0; - } - if(key = = Root->data) {//Find Success -*result =Root; + return 1; -}Else if(Key < Root->data) {//found element small root node element + returnBst_search (Root->lchild, key, root, result);//continue searching in Zuozi A}Else{//The lookup element is greater than the root node element. at returnBst_search (Root->rchild, key, root, result);//continue to find in right subtree - } -}
Based on the implementation of the search, we can implement the insert (construct) function of the two-fork lookup tree:
1 /*2 * * @brief the insertion of binary sort tree3 * * @retval when there are no data elements in the binary tree root that are equal to key4 * * Insert key and return 1, otherwise direct return 05 */6 intBst_insert (BITRNODEPTR *root, Treeelemtype key)7 {8Bitrnodeptr result = NULL, S =NULL;9 if(! Bst_search (*root, Key, NULL, &result)) {//Find not successfulTens = (bitrnodeptr)malloc(sizeof(Bitrnode)); OneS->data =key; AS->lchild = S->rchild =NULL; - - if(Result = =NULL) { the*root = s;//Insert node S as new root node -}Else if(Key < Result->data) { -Result->lchild = s;//Insert node S for left child -}Else{ +Result->rchild = s;//Insert node S for right child - } + A return 1;//Insert Successful at}Else{//a node with the same keyword already exists in the tree and is no longer inserted - return 0;//Insert Failed - } -}
In order to verify, we can implement a two-fork tree in the middle sequence traversal:
1 /*2 * * Sequential traversal of binary sort tree3 */4 voidBst_traverse (bitrnodeptr root,void(*visit) (bitrnodeptr))5 {6 if(Root = NULL)return;7Bst_traverse (root->Lchild, visit);8 visit (root);9Bst_traverse (root->Rchild, visit);Ten}
Finally, we give a test code:
1#include <stdio.h>2#include"search.h"3 4 voidvisit (bitrnodeptr e)5 {6printf"%c", e->data);7 }8 9 intMainvoid)Ten { OneBitrnodeptr root =NULL; A Treeelemtype key; - -scanf"%c", &key); the while(Key! ='#'){ -Bst_insert (&root, key); -scanf"%c", &key); - } + Bst_traverse (root, visit); - + return 0; A}
Binary sort Tree