话不多说,直接上代码
#include <iostream>
using namespace std;
template<typename T>
struct Node{
T val;
Node * left, *right;
Node(T v):val(v), left(nullptr), right(nullptr){}
};
template<typename T>
void printBst(Node<T> * root){
if(root == nullptr) return;
//先序遍历
printBst(root->left);
//中序遍历
cout <<" "<< root->val << " ";
printBst(root->right);
//后序遍历
}
template<typename T>
Node<T>* insert(Node<T> * node, T val){
if(node == nullptr) return new Node<T>(val);
if(node->val < val) node->right = insert(node->right, val);
else if(node->val > val) node->left = insert(node->left, val);
return node;
}
template<typename T>
Node<T>* minRightT(Node<T> * node){
//此处严禁更改node的指向,会乱套
Node<T> * current = node;
while(current->left != nullptr)
current = current->left;
return current;
}
template<typename T>
Node<T>* deletNode(Node<T> * node, T val){
if(node == nullptr) return node;
if(node->val > val) node->left = deletNode(node->left, val);
else if(node->val < val) node->right = deletNode(node->right, val);
else{
if(node->left == nullptr && node->right == nullptr) {delete node; return nullptr;}
else if(node->left != nullptr && node->right != nullptr){
Node<T> * minR = minRightT(node->right);
node->val = minR->val;
node->right = deletNode(node->right, minR->val);//这里的参数一定要用node->right保持树的根节点
}
else{
Node<T> *temp = (node->left == nullptr ? node->right : node->left);
delete node;
return temp;
}
}
return node;
}
class Student
{
public:
Student() {cout <<"默认Constructor"<< endl;}
Student(int score) {this->score = score;}
Student(const Student &a) {this->score = a.score;}
int getScore(){return this->score;}
void setScore(int score){this->score = score;}
bool operator<(const Student &a){return this->score < a.score;}
bool operator>(const Student &a){return this->score > a.score;}
bool operator>=(const Student &a){return !(*this<a);}//由于优先级,注意要加括号
void operator=(const Student &a){this->score = a.score;}
bool operator==(const Student &a){return this->score == a.score;}
friend ostream & operator<<(ostream & os, const Student &a);//注意要使用friend友元
private:
int score;
};
ostream & operator<<(ostream & os, const Student &a){
os<<"score:"<<a.score; return os;
}
int main(){
Node<int>* root = nullptr;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printBst(root);
cout << endl;
root = deletNode(root, 80);
printBst(root);
root = deletNode(root, 50);
cout << endl;
printBst(root);
cout<<endl;
Node<Student>* rootStu = nullptr;
rootStu = insert(rootStu, Student(50));
insert(rootStu, Student(30));
insert(rootStu, Student(20));
insert(rootStu, Student(40));
insert(rootStu, Student(70));
insert(rootStu, Student(60));
insert(rootStu, Student(80));
printBst(rootStu);
cout << endl;
}
新人一枚,错误和纰漏在所难免,还请各位圈中大佬指点一二。