#include <iostream>
#include <Windows.h>
using namespace std;
struct TreeNode
{
int key;
TreeNode *LChildNode;
TreeNode *RChildNode;
TreeNode(int &e, TreeNode *lchild, TreeNode *rchild)
:key(e), LChildNode(lchild), RChildNode(rchild){}
};
class BinaryTree
{
public:
void DeleteNode(TreeNode *n);
BinaryTree();
~BinaryTree();
void insert(int e);
int find(const int &e);
void findanddelete(int&e);
private:
TreeNode *m_root;
};
BinaryTree::~BinaryTree()
{}
BinaryTree::BinaryTree()
{
m_root = NULL;
}
void BinaryTree::DeleteNode(TreeNode *n)
{ TreeNode* temp = n;
if(n!=NULL) {
if(n->LChildNode&&n->RChildNode==NULL)
{
n=n->LChildNode;
delete temp;
}
if(!n->LChildNode&&n->RChildNode)
{
n=n->RChildNode;
delete temp;
}
else
{
temp=n->LChildNode;
while(temp->RChildNode)
{
temp=temp->RChildNode;
}
n->key=temp->key;
DeleteNode(temp);
}
}
else
return;
}
void BinaryTree::insert( int e )
{
if (!m_root)
{
m_root = new TreeNode(e,NULL,NULL);
return;
}
TreeNode *pNode = m_root;
while(pNode)
{
if (e > pNode->key)
{
if (pNode->RChildNode == NULL)
{
pNode->RChildNode = new TreeNode(e,NULL,NULL);
cout << "insert tree node: " << e << " succeed!" <<endl;
break;
}
pNode = pNode->RChildNode;
}
else if (e < pNode->key)
{
if (pNode->LChildNode == NULL)
{
pNode->LChildNode = new TreeNode(e,NULL,NULL);
cout << "insert tree node: " << e << " succeed!" <<endl;
break;
}
pNode = pNode->LChildNode;
}
else break;
}
Sleep(500);
}
int BinaryTree::find( const int &e )
{
TreeNode *pNode = m_root;
while(pNode)
{
if (e < pNode->key)
{
pNode = pNode->LChildNode;
}
else if (e > pNode->key)
{
pNode = pNode->RChildNode;
}
else break;
}
if(pNode)
{
cout << "The elem: " << e
<< " had find in tree."<< endl;
Sleep(500);
return 1;
}
else
return 0;
}
int main()
{
BinaryTree Bitree;
Bitree.insert(5);
Bitree.insert(3);
Bitree.insert(4);
Bitree.insert(2);
Bitree.insert(8);
Bitree.insert(7);
Bitree.insert(1);
int elem = 1;
Bitree.find(elem);
return 0;
}
binary search tree
最新推荐文章于 2024-05-29 15:37:18 发布