二叉搜索树(C++) 分类: C/C++ 数据结构与算法 2015-07-09 11:18 205人阅读 评论(0) 收藏

#include <iostream>

using namespace std;

typedef struct BiTNode{
	int data;
	struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;

class solution{
public:
	bool searchBst(BiTree root, int key, BiTree f, BiTree *p)
	{
		if (!root)
		{
			*p = f;
			return false;
		}
		else if (root->data == key)
		{
			*p = root;
			return true;
		}
		else if (key < root->data)
		{
			searchBst(root->lchild, key, root, p);
		}
		else
		{
			searchBst(root->rchild, key, root, p);
		}
	}

	bool insertNode(BiTree *root,int key)
	{
		BiTree p;
		if (!searchBst(*root, key, NULL, &p))
		{
			BiTNode* s = new BiTNode;
			s->data = key;
			s->lchild = s->rchild = NULL;
			if (!p)
			{
				*root = s;
			}
			else if (key < p->data)
			{
				p->lchild = s;
			}
			else
			{
				p->rchild = s;
			}

			return true;
		}
		else
		{
			return false;
		}
	}
	
	void printTree(BiTree root)
	{
		if (root == NULL)
			return;
		printTree(root->lchild);
		cout << root->data << "  ";
		printTree(root->rchild);
	}

	BiTNode* maxValue(BiTree root)
	{
		if (!root)
			return NULL;
		BiTNode* s = root;
		while (s->rchild)
		{
			s = s->rchild;
		}
		return s;
	}

	BiTNode* minValue(BiTree root)
	{
		if (!root)
			return NULL;
		BiTNode* s = root;
		while (s->lchild)
		{
			s = s->lchild;
		}
		return s;
	}

	bool Delete(BiTree* p)
	{
		BiTree q,s;	
		if ((*p)->lchild == NULL)
		{
			BiTree q = *p;
			*p = (*p)->rchild;
			delete q;
		}
		else if ((*p)->rchild == NULL)
		{
			BiTree q = *p;
			*p = (*p)->lchild;
			delete q;
		}
		else
		{
			s = (*p)->lchild;
			q = *p;
			while (s->rchild)
			{
				q = s;
				s = s->rchild;
			}
			(*p)->data = s->data;
			if (*p == q)
			{
				q->lchild = s->lchild;
			}
			else
			{
				q->rchild = s->lchild;
			}
			delete s;
		}
		return true;	
	}

	bool DeleteBST(BiTree* root, int key)
	{
		if (!root && !(*root))
			return false;
		else
		{
			if (key == (*root)->data)
				Delete(root);
			else if (key < (*root)->data)
				return DeleteBST(&((*root)->lchild), key);
			else
				return DeleteBST(&((*root)->rchild), key);
		}		
	}
};

int main()
{
	solution s;
	BiTree root=NULL;
	int a[10] = { 6, 4, 8, 5, 0, 9, 3, 7, 1, 2 };
	for (int i = 0; i < 10; ++i)
	{
		s.insertNode(&root, a[i]);
	}

	cout << "前序遍历结果:" << endl;
	s.printTree(root);
	cout << endl;
	cout << "最大值:" << endl;
	cout << (s.maxValue(root))->data << endl;
	cout << "最小值:" << endl;
	cout << (s.minValue(root))->data << endl;
	cout << "查找值为'3'的结点:" << endl;
	BiTree p;
	cout << (s.searchBst(root, 3, NULL, &p) ? "exist" : "no exist" )<< endl;
	cout << (s.searchBst(root, 8, NULL, &p) ? "exist" : "no exist") << endl;
	cout << (s.searchBst(root, 13, NULL, &p) ? "exist" : "no exist") << endl;
	cout << "删除值为3的结点:" << endl;
	s.DeleteBST(&root, 3);
	s.printTree(root);
	cout << endl;

	return 0;
}

posted @ 2015-07-09 11:18  朱传林  阅读(182)  评论(0编辑  收藏  举报