最近复习到二叉排序树,让自己对树的概念理解的更加清晰了。
贴上自己的代码供大家参考学习用。
最关键的是二叉排序树的删除操作。
#include<bits/stdc++.h>
using namespace std;
typedef struct node * tree_point;
struct node
{
int data;
tree_point lchild, rchild;
};
int n, a[105];
//创建二叉排序树,不断往里插入
void insert(tree_point &T, int x) {
if (T == NULL) {
T = new node;
T->data = x;
T->lchild = T->rchild = NULL;
}
else if (x == T->data)
return;
else if (x < T->data)
insert(T->lchild, x);
else insert(T->rchild, x);
}
void create(tree_point &T) {
T = NULL;
for (int i = 0; i < n; i++)
insert(T, a[i]);
}
//关键删除:1.删除的是叶子节点2,删除的节点仅有一边子树3.删除的节点带有左右两颗子树
//叶节点直接删除即可,单边子树的话,删除之前用子树替代自己
//两棵子树的话,选择直接前驱或(或者直接后继)替代当前节点,然后删除前驱(或者后继)即可。
void delete_node(tree_point &T) {
//T为父节点的孩子节点的指针的引用
tree_point temp, s;
//单子树情况(叶子节点也归纳到当中了)
if (T->lchild == NULL) {
temp = T;
T = T->rchild;
free(temp);
}
else if (T->rchild == NULL) {
temp = T;
T = T->lchild;
free(temp);
}
else {
temp = T; s = temp->lchild;
while (s->rchild) {
temp = s;
s = s->rchild;
}
T->data = s->data;
if (temp != T)
temp->rchild = s->lchild;
else temp->lchild = s->rchild;
free(s);
}
}
void delete_tree(tree_point &T, int x) {
if (T == NULL)return;
else {
if (T->data == x)delete_node(T);
else if (T->data > x)delete_tree(T->lchild,x);
else delete_tree(T->rchild, x);
}
}
void preorder(tree_point T) {
if (T) {
cout << T->data;
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(tree_point T) {
if (T) {
inorder(T->lchild);
cout << T->data;
inorder(T->rchild);
}
}
void postorder(tree_point T) {
if (T) {
postorder(T->lchild);
postorder(T->rchild);
cout << T->data;
}
}
void levelorder(tree_point T) {
queue<tree_point>q;
tree_point temp;
while (!q.empty())q.pop();
q.push(T);
while (!q.empty()) {
temp = q.front();
q.pop();
cout << temp->data;
if (temp->lchild)q.push(temp->lchild);
if (temp->rchild)q.push(temp->rchild);
}
}
void pt_all(tree_point T) {
preorder(T);
cout << endl;
inorder(T);
cout << endl;
postorder(T);
cout << endl;
levelorder(T);
cout << endl;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
tree_point T;
create(T);
pt_all(T);
int del_num;
cin >> del_num;
delete_tree(T, del_num);
pt_all(T);
return 0;
}