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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> using namespace std;
typedef int DataType; typedef struct BST_Node { DataType data; struct BST_Node *lchild, *rchild; }BST_T, *BST_P;
BST_P Search_BST(BST_P root, DataType key) { if (root == NULL) return NULL; if (key > root->data) return Search_BST(root->rchild, key); else if (key < root->data) return Search_BST(root->lchild, key); else return root; } void Insert_BST(BST_P *root, DataType data) { BST_P p = (BST_P)malloc(sizeof(struct BST_Node)); if (!p) return; p->data = data; p->lchild = p->rchild = NULL; if (*root == NULL) { *root = p; return; } if (Search_BST(*root, data) != NULL) return; BST_P tnode = NULL, troot = *root; while (troot) { tnode = troot; troot = (data < troot->data) ? troot->lchild : troot->rchild; } if (data < tnode->data) tnode->lchild = p; else tnode->rchild = p; }
void CreateBST(BST_P *T, int a[], int n) { int i; for (i = 0; i < n; i++) { Insert_BST(T, a[i]); } }
void MidOrderTraverse(BST_P T) { if (T) { MidOrderTraverse(T->lchild); cout << T->data << " "; MidOrderTraverse(T->rchild); } } int main(void) { int arr[] = { 17,12,19,10,15,18,25,8,11,13,16,22 }; BST_P root = NULL; cout << "数据为: "; for (int i = 0; i < 12; i++) cout << arr[i] << " "; cout << endl; CreateBST(&root, arr, 12); cout << "创建后中序遍历: "; MidOrderTraverse(root); int data = 0; cout << "\n输入查找元素: "; cin >> data; BST_P result = Search_BST(root, data); if (result) { cout << "数据为: " << result->data << "地址为: " << result << endl; } else { cout << "未查询到,插入后遍历:" ; Insert_BST(&root, data); MidOrderTraverse(root); } cout << endl; cout << "\n输入查找元素: "; cin >> data; result = Search_BST(root, data); if (result) { cout << "数据为: " << result->data << "地址为: " << result << endl; } else { cout << "未查询到,插入后遍历:" ; Insert_BST(&root, data); MidOrderTraverse(root); } cout << endl; system("pause"); return 0; }
|