Created
November 30, 2017 06:27
-
-
Save petriichuk/d4bd9ba2683f9e6a0399d454f67b2665 to your computer and use it in GitHub Desktop.
Binary Search Tree c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// bts | |
// | |
// Created by Taras Petriichuk on 30/11/2017. | |
// Copyright © 2017 Taras Petriichuk. All rights reserved. | |
// | |
#include <iostream> | |
using namespace std; | |
struct BsdNode{ | |
int data; | |
BsdNode* lowerPtr; | |
BsdNode* greaterPtr; | |
}; | |
BsdNode* createNode(int data){ | |
BsdNode* NewNode = new BsdNode(); | |
NewNode->data=data; | |
NewNode->lowerPtr=NULL; | |
NewNode->greaterPtr=NULL; | |
return NewNode; | |
} | |
BsdNode* InsertNode(BsdNode* root, int data){ | |
if(root==NULL){ | |
root=createNode(data); | |
return root; | |
} | |
else if (data<=root->data){ | |
root->lowerPtr=InsertNode(root->lowerPtr,data); | |
} | |
else{ | |
root->greaterPtr=InsertNode(root->greaterPtr,data); | |
} | |
return root; | |
} | |
bool Search(BsdNode* root, int data){ | |
if(root==NULL){ | |
return false; | |
} | |
else if(root->data==data){ | |
return true; | |
} | |
else if(root->data>data){ | |
return Search(root->lowerPtr, data); | |
} | |
else{ | |
return Search(root->greaterPtr, data); | |
} | |
} | |
int main(int argc, const char * argv[]) { | |
int UserInData; | |
int TryAgain=1; | |
BsdNode* root=NULL; | |
root=InsertNode(root, 5); | |
root=InsertNode(root, 15); | |
root=InsertNode(root, 25); | |
root=InsertNode(root, 35); | |
while(TryAgain){ | |
cout<<"Type the number u need to check:\n"; | |
cin>>UserInData; | |
if(Search(root, UserInData)){ | |
cout<<"Found\n"; | |
} | |
else{ | |
cout<<"Not found\n"; | |
} | |
cout<<"Try again? (1 - yes, 0 - Nope)\n"; | |
cin>>TryAgain; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment