您的位置:首页 > 编程语言 > C语言/C++

《算法导论》12、二叉查找树(C++实现)

2015-05-27 15:37 686 查看
没啥好说的,都是书上的功能。

#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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: