关闭

二叉搜索树(C++)

551人阅读 评论(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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:108751次
    • 积分:2602
    • 等级:
    • 排名:第14619名
    • 原创:143篇
    • 转载:53篇
    • 译文:1篇
    • 评论:13条
    博客专栏