#include <iostream>
using namespace std;
typedef struct TreeNode{
int val;
TreeNode*left;
TreeNode*right;
TreeNode*pre;//指向父节点的指针
}*TreePoint;
//采用循环而非递归的插入树节点。
void Tree_Insert(TreePoint& root,int key)
{
TreePoint x=root,y=NULL;
//树中有节点时找到插入节点需要插入的位置
while (x!=NULL)
{
y=x;
if (key<x->val)
{
x=x->left;
}
else
x=x->right;
}
if (y==NULL)//树为空时
{
root=new TreeNode;
root->val=key;
root->left=root->right=root->pre=NULL;
}
else
{
if (key<y->val)
{
y->left=new TreeNode;
y->left->val=key;
y->left->pre=y;
y->left->left=y->left->right=NULL;
}
else
{
y->right=new TreeNode;
y->right->val=key;
y->right->pre=y;
y->right->left=y->right->right=NULL;
}
}
}
//中序遍历树
void Print_Tree(TreePoint root)
{
if (root==NULL)
{
return ;
}
Print_Tree(root->left);
cout<<root->val<<" ";
Print_Tree(root->right);
}
TreePoint Tree_Search(TreePoint root,int key)
{
while (root!=NULL&&root->val!=key)
{
if (key<root->val)
{
root=root->left;
}
else
root=root->right;
}
return root;
}
TreePoint Tree_Max(TreePoint root)
{
while (root->right)
{
root=root->right;
}
return root;
}
//找到树中最小元素。
TreePoint Tree_Min(TreePoint root)
{
while (root->left)
{
root=root->left;
}
return root;
}
//找到某个节点中序遍历情况下的后继节点。
TreePoint Tree_SUCCESSOR(TreePoint x)
{
if (x->right!=NULL)
{
return Tree_Min(x->right);
}
TreePoint y;
y=x->pre;
while (y!=NULL&&x==y->right)
{
x=y;
y=y->pre;
}
return y;
}
//来自算法导论第二版P156.Z指针指向需要删除的元素
void Tree_Delete(TreePoint root,TreePoint z)
{
TreePoint x=NULL,y;
if (z->left==NULL||z->right==NULL)
{
y=z;
}
else
y=Tree_SUCCESSOR(z);
if (y->left!=NULL)
{
x=y->left;
}
else
x=y->right;
if (x!=NULL)
{
x->pre=y->pre;
}
if (y->pre==NULL)
{
root=x;
}else if (y==y->pre->left)
{
y->pre->left=x;
}
else
y->pre->right=x;
if (y!=z)
{
z->val=y->val;
}
}
int main()
{
TreePoint root=NULL;
int a[12]={15,5,16,3,12,20,10,13,18,23,6,7};
for (int i=0;i<12;i++)
{
Tree_Insert(root,a[i]);
}
cout<<"中序遍历树结果\n";
Print_Tree(root);
cout<<endl;
TreePoint p=Tree_Search(root,15);
if (p)
{
cout<<"find this element \n";
}
else
cout<<"not found \n";
cout<<"输出搜索值的后继节点\n";
cout<<Tree_SUCCESSOR(p)->val<<endl;
cout<<"删除树中元素\n";
Tree_Delete(root,p);
Print_Tree(root);
cout<<endl;
return 0;
}
二叉查找树(来自算法导论)
最新推荐文章于 2021-11-29 21:44:44 发布