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

二叉查找树——算法导论第12章简易代码实现~

2011-08-07 01:12 656 查看
本文对《算法导论》第12章二叉查找树的具体实现代码:

#ifndef _BINARY_SEARCH_TREE
#define _BINARY_SEARCH_TREE

typedef struct _Node
{
int val; // 值
struct _Node* left; // 左孩子
struct _Node* right; // 右孩子
} Node, *PNode;
#define NODE_SIZE sizeof(Node)
typedef PNode BTree;// 定义树

/* 将结点插入二叉查找树中 */
void insert_node_to_tree(BTree& tree, PNode n);
/* 根据所传入数组值创建结点并插入树中 */
void insert_values_to_tree(BTree& tree, int vals[], int n);
/* 以中序遍历显示树 */
void vist_tree_in_middle(const BTree tree);
/* 删除二叉树值 */
del_value_from_tree(BTree& tree, int val);

#endif


#include "binary_search_tree.h"
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void insert_node_to_tree(BTree& tree, PNode n)
{
PNode p, q;
p = tree;
q = NULL;
// 若为空树,则此插入结点即为树根~
if(tree==NULL)
{
tree = n;
return;
}

while(p)
{
q = p;
if(n->val < p->val)
p = p->left;
else
p = p->right;
}
if(n->val < q->val)
q->left = n;
else
q->right = n;
}

void insert_values_to_tree(BTree& tree, int vals[], int n)
{
PNode p = NULL;
for(int i = 0; i < n; i++)
{
p = (PNode)malloc(NODE_SIZE);
p->left = p->right = NULL;
p->val = vals[i];
insert_node_to_tree(tree, p);
}
}

void vist_tree_in_middle(const BTree tree)
{
if(NULL==tree)
return;
vist_tree_in_middle(tree->left);
printf("%-4d", tree->val);
vist_tree_in_middle(tree->right);
}

del_value_from_tree(BTree& tree, int val)
{
PNode p, q, r, s; // q为要删除结点s的前驱,p为val结点,r为删除结点,s为后继结点
q = NULL;
p = tree;
while(p && val!=p->val)
{
q = p;
p = (val < p->val)?p->left:p->right;
}

if(!p)
return;

// 如果只有左孩子,或右孩子的情况,则直接删除,将后继接上即可
if(p->left==NULL || p->right==NULL)
{
r = p;
}
else
{ // 如果都左右孩子,则将右子树的最左结点选择删除,将后继接上,并将该结点赋值与p。
q=p;
r=p->right;
while(r->left)
{
r = r->left;
}
}
// 将s指定为后继指针
if(r->left!=NULL)
{
s = r->left;
}
else
{
s = r->right;
}
// 若s有后继,则将其后继续到q上~
if(q==NULL)
{
tree = s;
}
else if(q->left==r)
{
q->left = s;
}
else
{
q->right = s;
}

if(p!=r)
{
p->val = s->val;
}
free(r);
}

void main()
{
BTree tree = NULL;
int vals[10] = {6, 12, 7, 9, 17, 8, 10, 5, 11, 16};

insert_values_to_tree(tree, vals, 10);
vist_tree_in_middle(tree);
printf("\n\nAfter deleteing the number 7, the tree is:\n");
del_value_from_tree(tree, 7);
vist_tree_in_middle(tree);
printf("\n");
}


附运行截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: