Ternary Search Trees 三分搜索树-源码

#include 
#include 
#include 
#include 
using namespace std;

class TernarySearchTree
{

private:

	struct tnode
	{
		char s;
		tnode *lkid, *mkid, * rkid;
		bool mbEnd;

		tnode(char is)
		{
			s = is;
			lkid = NULL;
			mkid = NULL;
			rkid = NULL;
			mbEnd = false;

		}

	};
	tnode* root;
private:

	void hInsert(tnode** p, const char *s, char* originalS)
	{
		if(*p == NULL)
		{
			*p = new tnode(*s);
		}

		if((*p)->s > *s)
		{
			hInsert(&((*p)->lkid), s, originalS);
		}
		else if((*p)->s < *s)
		{
			hInsert(&((*p)->rkid), s, originalS);
		}
		else
		{
			if(*(s + 1) == '\0')
			{
				(*p)->mbEnd = true;
				(*p)->mkid = (tnode*)(originalS);
				return;
			}
			hInsert(&((*p)->mkid), s + 1, originalS);
		}

	}

	void hBuildTST(vector& ivString, int istart, int iend)
	{
		if(istart > iend) return;

		int mid = (istart + iend)/ 2;

		Insert(ivString[mid].c_str());

		hBuildTST(ivString, istart, mid -1);

		hBuildTST(ivString, mid + 1, iend);

	}

	void hTraverse(tnode* inode)
	{
		if(inode == NULL) return;

		hTraverse(inode->lkid);
		if(inode->mbEnd) cout << (char*)(inode->mkid) << endl;
		else	hTraverse(inode->mkid);

		hTraverse(inode->rkid);
	}

public:

	TernarySearchTree()
	{
		root = NULL;
	}

	void Insert(const char *s)
	{
		int slength = strlen(s);
		char* CopyS = new char[slength + 1];
		memcpy(CopyS, s, sizeof(char)* (slength+1));
		hInsert(&root, s, CopyS);
	};


	void BuildTST(vector& ivString)
	{

		sort(ivString.begin(), ivString.end());

		hBuildTST(ivString, 0, ivString.size() - 1);
	}

	

	bool find(const char *s)
	{
		if(root == NULL)
			return false;
		const char* lps = s;

		tnode* lp = root;

		while(true)
		{

			if(lp->s < *lps)
			{
				lp = lp->rkid;
			}
			else if(lp->s > *lps)
			{
				lp = lp->lkid;
			}
			else
			{

				if(*(lps + 1) == '\0' && lp->mbEnd)
					return true;

				lp = lp->mkid;
				lps++;
			}

			if(lp == NULL)
				return false;

		}
		return false;

	}

	void Traverse()
	{
		hTraverse(root);
	}

};
// ternary_Search_tree.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "TernarySearchTree.h"
#include 
#include 
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	TernarySearchTree lTST;

	char* lTestString[] = {"as", "at", 

				"be", "by", "he", "in",

				"is", "it", "of", "on",

				"or", "to"};

	//for(int i = 0; i< sizeof(lTestString)/sizeof(char*); i++)

	//	lTST.Insert(lTestString[i]);

	vector lvTestString;

	for(int i = 0; i< sizeof(lTestString)/sizeof(char*); i++)

		lvTestString.push_back(string(lTestString[i]));

	lTST.BuildTST(lvTestString);

	lTST.Traverse();

	string input;
	while(cin >> input)
	{

		if(lTST.find(input.c_str()))

		{

			cout << "find it" << endl;

		}

		else

		{

			cout << "can not find it" << endl;

		}

	}

	

	return 0;
}


你可能感兴趣的:(算法和数据结构学习)