带有父节点的二叉查找树实现

看来得要个父节点,因为后面的红黑树很需要啊!!

 

《带有父节点的二叉查找树实现》
《带有父节点的二叉查找树实现》
代码

   
    
    #include 
    <
    iostream
    >
    
using namespace std;
struct tree
{
int data;
tree
* left, * right, * parent;
};
void tree_insert(tree *& , int );
// 二叉查找树的初始化构建
void tree_init(tree *& T)
{
cout
<< " please input numbers of tree until the input is invalid " << endl;
int data = 0 ;
while (cin >> data)
{
tree_insert(T, data);
}
}
// 插入
void tree_insert(tree * & T, int value)
{
if (T == NULL)
{
T
= new tree();
T
-> data = value;
T
-> left = T -> right = T -> parent = NULL;
}
else
{
if (T -> data > value)
{
tree_insert(T
-> left, value);
if (T -> left)
T
-> left -> parent = T;
}
else
{
tree_insert(T
-> right, value);
if (T -> right)
T
-> right -> parent = T;
}
}
}
// preorder to print the data of the whole tree
void tree_print1(tree * T)
{
if (T != NULL)
{
tree_print1(T
-> left);
cout
<< T -> data << " " ;
tree_print1(T
-> right);
}
}
// 中序遍历
void tree_print2(tree * T)
{
if (T != NULL)
{
tree_print2(T
-> right);
cout
<< T -> data << " " ;
tree_print2(T
-> left);
}
}
// 后序遍历
void tree_print3(tree * T)
{
if (T != NULL)
{
cout
<< T -> data << " " ;
tree_print3(T
-> left);
tree_print3(T
-> right);
}
}
// find a value in the tree with the method of recursion
bool tree_search(tree * T, int value)
{
tree
* t = T;
while (t != NULL)
{
if (t -> data == value)
{
return true ;
}
if (t -> data < value)
t
= t -> right;
else
t
= t -> left;
}
return false ;
}
// 求最小值
tree * tree_mininum(tree * T)
{
while (T && T -> left)
{
T
= T -> left;
}
return T;
}
// 求后继结点
tree * tree_successor(tree * T)
{
if ( ! T -> right)
{
return tree_mininum(T -> right);
}
tree
* y = T -> parent;
while (y && T == y -> right)
{
T
= y;
y
= y -> parent;
}
return y;
}
// 删除节点,不考虑性质
void del1(tree *& t)
{
if (t == t -> parent -> left)
{
if ( ! t -> left && ! t -> right)
t
-> parent -> left = NULL;
if (t -> left != NULL)
t
-> parent -> left = t -> left;
if (t -> right != NULL)
t
-> parent -> left = t -> right;
}
else
{
if ( ! t -> left && ! t -> right)
t
-> parent -> right = NULL;
if (t -> left != NULL)
t
-> parent -> right = t -> left;
if (t -> right != NULL)
t
-> parent -> right = t -> right;
}
}
// 删除任意节点,并保持二叉查找树的性质
void tree_del(tree * T)
{
tree
* y = NULL;
if (T -> left == NULL || T -> right == NULL)
{
y
= T;
del1(T);
}
else
{
y
= tree_successor(T);
T
-> data = y -> data;
del1(y);
}

}

int main()
{
tree
* T = NULL;
tree_init(T);
cout
<< " The number in the tree is : " << endl;
tree_print1(T);
cout
<< endl;
tree_print2(T);
cout
<< endl;
tree_print3(T);
int find_value = 0 ;
// cout << endl << "please input the number you want to find" <<endl;
cin.clear();
// cin >> find_value;
// cout << tree_search(T,find_value) << endl;
int del_data = 0 ;
cin
>> del_data;
tree_del(T);
}

 

 

 

    原文作者:hailong
    原文地址: https://www.cnblogs.com/xiangshancuizhu/archive/2010/12/05/1897241.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞