1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #include <stdio.h> #include <stdlib.h>
typedef int KeyType; typedef struct BSTNode { KeyType key; struct BSTNode *lchild, *rchild; } BSTNode, *BiTree;
int insertBST(BiTree &T, KeyType k) { BiTree treeNew = (BiTree) calloc(1, sizeof(BSTNode)); treeNew->key = k; if (NULL == T) { T = treeNew; return 1; } BiTree p = T, parent; while (p) { parent = p; if (k > p->key) { p = p->rchild; } else if (k < p->key) { p = p->lchild; } else { return -1; } } if (k > parent->key) { parent->rchild = treeNew; } else { parent->lchild = treeNew; } return 0; }
void createBST(BiTree &T, KeyType *str, int len) { for (int i = 0; i < len; i++) { insertBST(T, str[i]); } }
void createBSTOrder(BiTree &T, KeyType *str, int len) { T = NULL; int i; while (i < len) { insertBST(T, str[i]); i++; } }
void inOrder(BiTree T, int arr[]) { static int pos = 0; if (T != NULL) { inOrder(T->lchild, arr); printf("%3d", T->key); arr[pos] = T->key; pos += 1; inOrder(T->rchild, arr); } }
int binarySearch(int arr[], KeyType key, int len) { int low = 0, mid, high = len - 1; while (low <= high) { mid = (low + high) / 2; if (key > arr[mid]) { low = mid + 1; } else if (key < arr[mid]) { high = mid - 1; } else { return mid; } } return -1; }
int main() { BiTree T = NULL; KeyType str[10] = {87, 7, 60, 80, 59, 34, 86, 99, 21, 3}; createBST(T, str, 10); inOrder(T, str); printf("\n"); int val = binarySearch(str, 21, 10); printf("%d", val); return 0; }
|