码迷,mamicode.com
首页 > 其他好文 > 详细

手写BST插入查找删除

时间:2014-06-10 08:09:49      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:search   算法   

binary search\sort\find tree operations


status InsertNode(Node* root, data x, Node* father)
{
	if(root==NULL)
	{
		if(father==NULL)
			Tree empty;
		else
		{
			if(x<father->data)
			{
				father->left=new Node//inital left right NULL
				father->left->data=x;
				return  success;
			}
			else if(father->data<x)
			{
				father->right=new Node;//inital left right NULL
				father->right->data=x;
				return succes;
			}
			else
			{
				return failure, have same data in BST//Hash also not allowed same data, but other such as array allow
			}
		}
	}
	if(x<root->data) InsertNode(root->left,x); //imitate big god fawks's code style : )
	else if(root->data<x) InsertNode(root->right,x);
	else
		return falure, have same data in BST;
}

后来发现,根本不需要father, 会出现上面的原因是我总以为指针为空,指针变量也不能在赋值了。有个错误理解,指针变量是一个变量,他的值为空,现在可以让他指向其他的地方,例如申请一个堆空间,他的值就是这个新的空间的地址值。




status InsertNode(Node* root, data x)
{
	if(root==NULL)
	{
		root=new Node;//assume initial left right NULL
		root->data=x;
	}
	if(x<root->data) InsertNode(root->left,x); //imitate big god fawks's code : )
	else if(root->data<x) InsertNode(root->right,x);
	else
		return falure, have same data in BST;
}





Node* FindNode(Node* root, data x, Node* father)//use father for delete recall
{
	if(root==NULL) return NULL;
	if(x<root->data) FindNode(root->left, x,root);
	else if(root0>data<x) FindNode(root->right,x,root);
	else
		return root;
}

status DeleteNode(Node* root, data x)
{
	Node* parent=NULL;
	Node* p=FindNode(root,x,parent);
	if(p==NULL)
		return failure, can not found x;
	if(parent==NULL)//BST only has a root
		return success root==NULL;//set BST as NULL
	if(p==parent->left)
	{
		if(p-left!=NULL)
		{
			move p's right child as p's leftchild's rightdownmost node's right child 
			parent->left=p->left;
		}
		else if(p->right!=NULL)
		{
			move p's left child as p's rightchild's leftdownmost node's left child;
			parent->left=p->right;
		}
		else// all null
		{
			parent->left==NULL;
		}
		delete p;
	}
	if(p==parent->right)
	{
		follow left part;
	}	
	return sucess;
}




总结指针bug就是 每次访问left right,都要考虑是否p为空,如果有空就另外处理,否则NULL访问left right 程序就crash了。

手写BST插入查找删除,布布扣,bubuko.com

手写BST插入查找删除

标签:search   算法   

原文地址:http://blog.csdn.net/richardzrc/article/details/29600939

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!