二叉查找树(来自算法导论)

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值