1️⃣8️⃣ 二叉查找树
😅 有空把Delete和中序、前序、后序遍历加进来。
#include <iostream>
using namespace std;
class BST;
class BstNode{
friend class BST;
private:
int data;
BstNode* LeftChild;
BstNode* RightChild;
void display(int i);
public:
int getdata(){return data;}
};
class BST{
private:
BstNode* root;
public:
BST(BstNode* init=0): root(init){}
bool Insert(const int);
bool Delete(const int);
BstNode* Search(const int);
BstNode* Search(BstNode*, int);
BstNode* IterSearch(const int);
void display(){
cout << endl;
if(root)
root->display(1);
else cout << "这是空树!" << endl;
}
};
void BstNode::display(int i){
cout << "Position: " << i << ", data: " << data << endl;
if(LeftChild) LeftChild->display(2*i);
if(RightChild) RightChild->display(2*i+1);
}
bool BST::Insert(const int d){
BstNode* p = root;
BstNode* q = 0; //q指向p的父节点
//insert之前要先查找
while(p){
q = p;
if(d == p->data) return false;
else if(d < p->data) p = p->LeftChild;
else p = p->RightChild;
}
//找到的位置就是q
p = new BstNode;
p->LeftChild = p->RightChild = 0;
p->data = d;
if(!root) root = p;
else if(d < q->data) q->LeftChild = p;
else q->RightChild = p;
return true;
}
bool BST::Delete(const int d){
BstNode* p = root;
BstNode* q = 0;
while(p){
if(d == p->data) break;
q = p;
else if(d < p->data) p = p->LeftChild;
else p = p->RightChild;
}
if(p == root){
if(root->LeftChild)
}
}
BstNode* BST::Search(const int x){
return Search(root, x);
}
BstNode* BST::Search(BstNode* b, const int x){
if(!b) return 0;
if(x == b->data) return b;
else if(x < b->data) return Search(b->LeftChild, x);
else return Search(b->RightChild, x);
}
BstNode* BST::IterSearch(const int x){
BstNode* t = root;
while(t){
if(x == t->data)
return t;
else if(x < t->data)
t = t->LeftChild;
else t = t->RightChild;
}
return 0;
}
int main(){
BST m;
m.Insert(5);
m.Insert(3);
m.Insert(8);
m.Insert(16);
m.Insert(9);
m.Insert(1);
m.Insert(24);
m.Insert(2);
m.display();
BstNode* p = m.Search(3);
cout << "找到的是:" << p->getdata() << endl;
BstNode* q = m.Search(9);
cout << "找到的是:" << q->getdata() << endl;
return 0;
}