Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created December 12, 2012 11:32
Show Gist options
  • Save shonenada/4267108 to your computer and use it in GitHub Desktop.
Save shonenada/4267108 to your computer and use it in GitHub Desktop.
Binary Sort Tree
struct BinNode {
int data;
BinNode *lChild, *rChild;
};
class BinSortTree{
public:
BinSortTree();
~BinSortTree();
void SearchBST(int);
void CreateBST(int *, int);
private:
BinNode* root;
BinNode* GetNode(int k);
void SearchNode(BinNode*, int);
void InsertNode(BinNode * root, BinNode *);
};
BinSortTree::BinSortTree(){
root = new BinNode;
root -> data = NULL;
root -> lChild = NULL;
root -> rChild = NULL;
}
void BinSortTree::CreateBST(int *r ,int n){
int i;
BinNode *s;
root->data = r[0];
for(i=1;i<n;i++){
s = new BinNode;
s->data = r[i];
s->lChild = NULL;
s->rChild = NULL;
InsertNode(root, s);
}
}
void BinSortTree::InsertNode(BinNode * root, BinNode* s){
if (s->data < root->data){
if (!root->lChild == NULL) {
InsertNode(root->lChild, s);
}
else{
root->lChild = s;
return ;
}
}else{
if(!root->rChild == NULL){
InsertNode (root->rChild, s);
}
else{
root->rChild = s;
return ;
}
}
}
void BinSortTree::SearchBST(int k){
if(root)
SearchNode(root, k);
}
void BinSortTree::SearchNode(BinNode* root, int k){
BinNode *NextBiNode;
if( root->data == k){
return;
}
else {
if(root->data > k){
NextBiNode = root->lChild;
}
else {
NextBiNode = root->rChild;
}
}
if(NextBiNode)
SearchNode(NextBiNode,k);
else{
if(root->data > k)
root->lChild=GetNode(k);
else root->rChild=GetNode(k);
}
}
BinNode* BinSortTree::GetNode(int k)
{
BinNode *s=new BinNode;
s->data=k;
s->lChild=NULL;
s->rChild=NULL;
return s;
}
BinSortTree::~BinSortTree(){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment