没啥好说的,都是书上的功能。
#include <iostream>
#include "stdio.h"
using namespace std;
struct Node
{
Node *p;
int value;
Node *left;
Node *right;
};
Node* root;
void inorderTreeWalk(Node* n)
{
if (n != NULL)
{
inorderTreeWalk(n->left);
cout << n->value << " ";
inorderTreeWalk(n->right);
}
}
Node* treeSearch(Node* n, int value)
{
if (n == NULL || n->value == value)
return n;
else
{
if (n->value > value)
return treeSearch(n->left, value);
else
return treeSearch(n->right, value);
}
}
Node* treeMin(Node* n)
{
Node* r=n;
while (r->left!=NULL)
{
r = r->left;
}
return r;
}
Node* treeMax(Node* n)
{
Node* r = n;
while (r->right != NULL)
{
r = r->right;
}
return r;
}
Node* treeSuccessor(Node* n)
{
Node* x = n;
if (n->right != NULL)
return treeMin(n->right);
Node* y = n->p;
while (y != NULL && x == y->right)
{
x = y;
y = y->p;
}
return y;
}
Node* treePredecessor(Node* n)
{
Node* x = n;
if (n->left != NULL)
return treeMax(n->left);
Node* y = n->p;
while (y != NULL && x == y->left)
{
x = y;
y = y->p;
}
return y;
}
Node* treeInsert(Node* n, int key)
{
Node* y = NULL;
Node* x = n;
if (x == NULL)
{
x = new Node;
x->p = NULL;
x->value = key;
x->left = NULL;
x->right = NULL;
root = x;
return x;
}
while (x != NULL)
{
y = x;
if (x->value > key)
x = x->left;
else
x = x->right;
}
x = new Node;
x->p = y;
x->value = key;
x->left = NULL;
x->right = NULL;
if (y != NULL)
{
if (key < y->value)
y->left = x;
else
y->right = x;
}
return x;
}
void treeDelete(Node* n, Node* z)
{
Node* x, * y;
if (z->left == NULL || z->right == NULL)
y = z;
else
y = treeSuccessor(z);
if (y->left != NULL)
x = y->left;
else
x = y->right;
if (x != NULL)
x->p = y->p;
if (y->p == NULL)
root=x;
else if (y == y->p->left)
y->p->left = x;
else
y->p->right = x;
if (y != z)
z->value = y->value;
delete y;
}
void treeDestroy(Node* n)
{
if (n != NULL)
{
treeDestroy(n->left);
treeDestroy(n->right);
delete n;
}
}
void main()
{
int n = 10; //排序元素长度
for (int i = 0; i <n; i++)
{
treeInsert(root, rand() % 1000);
}
inorderTreeWalk(root); //中序遍历
cout << endl;
Node* p = treeSearch(root, 962);
if (p != NULL)
{
cout << "结果:" << p->value << endl;
treeDelete(root, p); //删除节点
}
else
cout << "无该节点" << endl;
inorderTreeWalk(root); //中序遍历
cout << endl;
treeDestroy(root);
system("pause");
}