建树、中序遍历
#include
#include
#include
typedef int keyType;
typedef struct BSnode {
keyType key;
struct BSnode *left, *right;
} LBtree, *Btree;
int Binsert(Btree &tree, int num) {
Btree bNew = (Btree) calloc(1, sizeof(LBtree));
bNew->key = num;
if (tree == NULL) {
tree = bNew;
return 0;
}
Btree p, parent;//用来遍历
p = tree;
while (p) {
parent = p;//父节点
if (num > p->key) {
p = p->right;
} else if (num < p->key) {
p = p->left;
}
}
if (num > parent->key) {
parent->right = bNew;
} else {
parent->left = bNew;
}
return 0;
}
void creatTree(Btree &tree, int *arr, int length) {
for (int i = 0; i < length; i++) {
Binsert(tree, arr[i]);
}
}
void inOrder(Btree p) {
if (p) {
inOrder(p->left);
printf("%3d", p->key);
//递归
inOrder(p->right);
}
}
void searchTree(Btree tree, Btree &parent, int num) {
parent = NULL;
while (tree && tree->key != num) {
parent = tree;
if (num > tree->key) {
tree = tree->right;
} else if (num < tree->key) {
tree = tree->left;
}
}
printf("%d",tree->key);
}
int main() {
Btree tree = NULL;//树根
int arr[7] = {50, 20, 66, 40, 28, 79, 58};
creatTree(tree, arr, 7);
// inOrder(tree);
Btree parent;
searchTree(tree, parent, 28);
return 0;
}
删除
#include
#include
#include
typedef int keyType;
typedef struct BSnode {
keyType key;
struct BSnode *left, *right;
} LBtree, *Btree;
int Binsert(Btree &tree, int num) {
Btree bNew = (Btree) calloc(1, sizeof(LBtree));
bNew->key = num;
if (tree == NULL) {
tree = bNew;
return 0;
}
Btree p, parent;//用来遍历
p = tree;
while (p) {
parent = p;//父节点
if (num > p->key) {
p = p->right;
} else if (num < p->key) {
p = p->left;
}
}
if (num > parent->key) {
parent->right = bNew;
} else {
parent->left = bNew;
}
return 0;
}
void creatTree(Btree &tree, int *arr, int length) {
for (int i = 0; i < length; i++) {
Binsert(tree, arr[i]);
}
}
void inOrder(Btree p) {
if (p) {
inOrder(p->left);
printf("%3d", p->key);
//递归
inOrder(p->right);
}
}
void searchTree(Btree tree, Btree &parent, int num) {
parent = NULL;
while (tree && tree->key != num) {
parent = tree;
if (num > tree->key) {
tree = tree->right;
} else if (num < tree->key) {
tree = tree->left;
}
}
printf("%d", tree->key);
}
void deleteNode(Btree &tree, int num) {
if (tree == NULL) {
return;
}
if (tree->key > num) {
deleteNode(tree->left, num);
} else if (tree->key < num) {
deleteNode(tree->right, num);
} else {
if (tree->left == NULL) {
Btree tem = tree;
tree = tree->right;
free(tem);
} else if (tree->right == NULL) {
Btree tem = tree;
tree = tree->left;
free(tem);
} else {
Btree tem = tree->left;
while (tree->right) {
tem = tree->right;
}
tree->key = tem->key;
deleteNode(tree->left, tem->key);
}
}
}
int main() {
Btree tree = NULL;//树根
int arr[7] = {50, 20, 66, 40, 28, 79, 58};
creatTree(tree, arr, 7);
// inOrder(tree);
Btree parent;
// searchTree(tree, parent, 28);
deleteNode(tree, 40);
inOrder(tree);
return 0;
}