点击查看代码
//Inplementation of Binary Search Tree
#include<iostream>
using namespace std;
struct bstnode {
int data;
bstnode* left;
bstnode* right;
};
/*bstnode* root = NULL;*/
/*root = NULL; wrong*/
/*全局范围内的变量的初始化必须在声明的时候完成*/
bstnode* getnewnode(int x) {
bstnode* temp = new bstnode;
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}//创建新节点并返回地址
bstnode* insert(bstnode* root,int x) {//参数式递归
if (root == NULL) {//空树
root = getnewnode(x);//root指向新节点
return root;//递归中止
}
if (x <= root->data) {//插入数据较小以左边为子root建立新子树
root->left = insert(root->left, x);//左边子root指向新子树
}
else {//插入数据较大以右边为子root建立新子树
root->right = insert(root->right, x); //右边子root指向新子树
}
return root;//返回新树的头节点的地址
}//时间复杂度:O(logn)in best case(balanced bst)
bool search(bstnode* root, int x) {//副本即可
if (root == NULL) return false;
if (root->data == x) return true;
if (x <= root->data) return search(root->left, x);
else return search(root->right, x);
}//时间复杂度:O(logn)in best case(balanced bst)
int main() {
bstnode* root = NULL;
root = insert(root, 15);
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 25);
root = insert(root, 8);
root = insert(root, 12);
int n;
cin >> n;
if (search(root, n)) cout << "Found" << endl;
else cout << "Not Found\n";
}