算法导论实践中的教训

1 因为关键字,折腾很久,为何定义的结构体总是说没有这个定义,原来问题出现在没有用关键字typedef,这个关键字通俗点说就是别名的意思,可用用定义的别名来定义其他的变量或函数,当需要改变这个别名类型的时候,只要修改typedef定义就可以做到一改全改的目的,不用一个个去改变类型了。

2 今天因为在函数内部申请的内存,回到原函数是,申请的内存已经被释放了,百思不得其解,终于看到C++的伟大之处,使用引用&操作符,可以解决这个问题,Mark一下。

二叉查找树代码

#include <iostream>
using namespace std;

typedef int elemType;

typedef struct biNode
{
	struct biNode *parent,*left,*right;
	elemType key;
}*biTree;

int insertNode(biTree & root,elemType key)
{
	biTree x,y=NULL;
	biTree z=new biNode;

	z->key=key;
	z->parent=z->right=z->left=NULL;

	x=root;
	while (x!=NULL)
	{
		y=x;
		if (z->key<y->key)
			x=x->left;
		else
			x=x->right;
	}
	z->parent=y;
	if (y==NULL)
		root=z;
	else if (z->key<y->key)
		y->left=z;
	else
		y->right=z;
	return 0;
}
biTree treeSearch(biTree & root,elemType k)
{
	if (root==NULL||k==root->key)
		return root;
	if (k<root->key)
		return treeSearch(root->left,k);
	else
		return treeSearch(root->right,k);
	
}
biTree minNode(biTree root)
{
	biTree x=root;
	while (x->left==NULL)
		x=x->left;
	return x;
}

biTree successorNode(biTree root)
{
	biTree x=root;
	biTree y;
	if (x->right!=NULL)
		return minNode(x->right);
	y=x->parent;
	while (y!=NULL&&x==y->right)
	{
		x=y;
		y=y->parent;
	}
	return y;
}

biTree delNode(biTree & root,elemType k)
{
	biTree x=NULL,y=NULL;
	biTree z=treeSearch(root,k);
	if (z->left==NULL||z->right==NULL)
	{
		y=z;
	}
	else
		y=successorNode(z);
	if (y->left==NULL)
	{
		x=y->left;
	}
	else
		x=y->right;

	if (x!=NULL)
	{
		x->parent=y->parent;
	}
	if (y->parent==NULL)
	{
		root=x;
	}
	else if (y=y->parent->left)
	{
		y->parent->left=x;
	}
	else
		y->parent->right=x;

	if (y!=z)
	{
		z->key=y->key;
	}
	return y;
}

void InorderTreeWalk(biTree & root)
{
	if (root!=NULL)
	{
		InorderTreeWalk(root->left);
		cout<<root->key<<"-->";
		InorderTreeWalk(root->right);
	}

}
int main()
{
	biTree root=NULL;
	int num;
	cin>>num;
	for (int i=0;i<num;i++)
	{
		int temp;
		cout<<"input the "<<i+1<<" num :";
		cin>>temp;
		insertNode(root,temp);
	}
	InorderTreeWalk(root);
	if (treeSearch(root,10)->key==10)
	{
		cout<<"succeed!"<<endl;
	}
	else
		insertNode(root,10);
	InorderTreeWalk(root);
	delNode(root,10);
	InorderTreeWalk(root);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值