通过结构体作为节点,结构体包含四个成员,分别是键值key,指向父节点的指针 *parent,指向左子节点的指针 *left,指向右子节点的指针 *right。
struct Node{
int key;
Node *left,*right,*parent;
}
从根以起点寻找节点 x 的插入位置。 设当前节点为 x,如果 z 的键值小于 x 则将当前节点的左子节点作为下一个 x,反之则以右子节点作为下一个 x,如此不断向叶节点搜索。在此过程中,将 x 的前一个节点保存在 y 中,用作 z 的候选父节点。当x 到达 NIL 时结束搜索,此时的 y 节点就是 z 的父节点了。
#include <iostream>
#include <string>
using namespace std;
struct Node {
int key;
Node* left, * right, * parent;
};
Node* root, * NIL;
int H;
void InsertKey(int k) {
Node* x = root;
Node* y = NIL;
Node* z = new Node;
z->key = k;
z->left = NIL;
z->right = NIL;
while (x != NIL) {
y = x;
if (z->key < x->key) {
x = x->left;
}
else {
x = x->right;
}
}
z->parent = y;
if (y == NIL) {
root = z;
}
else {
if (y->key > z->key) {
y->left = z;
}
else {
y->right = z;
}
}
}
void PreOrder(Node* u) {
if (u == NIL)
return;
cout << u->key << " ";
PreOrder(u->left);
PreOrder(u->right);
}
void Inorder(Node* u) {
if (u == NIL)
return;
Inorder(u->left);
cout << u->key << " ";
Inorder(u->right);
}
int main()
{
int n, x;
string com;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> com;
if (com == "insert") {
cin >> x;
InsertKey(x);
}
else if (com == "print") {
printf("Inorder:");
Inorder(root);
printf("\n");
printf("Preorder:");
PreOrder(root);
printf("\n");
}
}
return 0;
}
/*
input:
8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print
*/
/*
out put:
Inorder: 1 12 17 20 25 30 88
Preorder: 30 12 1 20 17 25 88
*/
考察:设树高为h,向二叉搜索树中插入元素的操作的复杂度为O(h)。若输入平衡,算法的复杂度就是O(logn)。