二叉查找树的简单实现1
按照算法导论的伪代码实现的,灰常简单的实现!
二叉查找树的原理是节点不小于它的左孩子,小于右孩子。
#include <iostream> using namespace std; struct tree { int data; tree *left,*right; }; void tree_insert(tree *&, int); void tree_init(tree *&T) { cout << "please input numbers of tree until the input is invalid" << endl; int data = 0; while (cin >> data) { tree_insert(T, data); } } void tree_insert(tree * &T, int value) { if (T == NULL) { T = new tree(); T->data = value; T->left = T->right = NULL; } else { if (T->data > value) tree_insert(T->left, value); else tree_insert(T->right, value); } } //preorder to print the data of the whole tree void tree_print(tree *T) { if (T != NULL) { tree_print(T->left); cout << T->data << " "; tree_print(T->right); } } //find a value in the tree with the method of recursion bool tree_search(tree *T, int value) { tree *t = T; while (t != NULL) { if (t->data == value) { return true; } if(t->data < value) t = t->right; else t = t->left; } return false; } int main() { tree *T = NULL; tree_init(T); cout << "The number in the tree is :" << endl; tree_print(T); int find_value = 0; cout << endl << "please input the number you want to find" <<endl; cin.clear(); cin >> find_value; cout << tree_search(T,find_value) << endl; }