Created
December 8, 2014 01:32
-
-
Save darkrishabh/3cbf55d3743be6ea5d90 to your computer and use it in GitHub Desktop.
BST Traversal and Insertion
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
#include <iostream> | |
using namespace std; | |
struct BSTNode{ | |
int value; | |
BSTNode* left; | |
BSTNode* right; | |
}; | |
BSTNode* insert(BSTNode*, int); | |
BSTNode* GetNode(int); | |
bool Search(BSTNode*, int); | |
void preOrder(BSTNode*); | |
void postOrder(BSTNode*); | |
void InOrder(BSTNode*); | |
int main() { | |
BSTNode* root = NULL; | |
int n; | |
root = insert(root,7); | |
root = insert(root,9); | |
root = insert(root,5); | |
root = insert(root,4); | |
root = insert(root,8); | |
cout <<"PreOrder Traversal: " << endl; | |
preOrder(root); | |
cout <<"\n\nPostOrder Traversal: " << endl; | |
postOrder(root); | |
cout <<"\n\nInOrder Traversal: " << endl; | |
InOrder(root); | |
cout<< "\n Enter a number to Search: "; | |
cin>>n; | |
if(Search(root,n)) | |
cout << "Found"; | |
else | |
cout << "Not Found"; | |
return 0; | |
} | |
BSTNode* insert(BSTNode* root, int value){ | |
if(root == NULL){ | |
root = GetNode(value); | |
} | |
else if(value <= root->value){ | |
root->left = insert(root->left, value); | |
} | |
else | |
root->right = insert(root->right,value); | |
return root; | |
} | |
BSTNode* GetNode(int value){ | |
BSTNode* node = new BSTNode(); | |
node->value = value; | |
node->left = node->right = NULL; | |
return node; | |
} | |
bool Search(BSTNode* root, int value){ | |
if(root == NULL)return false; | |
else if(value == root->value) return true; | |
else if(value <= root->value) return Search(root->left, value); | |
else return Search(root->right, value); | |
} | |
void preOrder(BSTNode* root){ | |
if(root != NULL){ | |
cout << root->value << " "; | |
preOrder(root->left); | |
preOrder(root->right); | |
} | |
} | |
void postOrder(BSTNode* root){ | |
if(root != NULL){ | |
postOrder(root->left); | |
postOrder(root->right); | |
cout << root->value << " "; | |
} | |
} | |
void InOrder(BSTNode* root){ | |
if(root != NULL){ | |
postOrder(root->left); | |
cout << root->value << " "; | |
postOrder(root->right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment