Created
December 6, 2017 11:40
-
-
Save ArtyomLazyan/2f32af8e2b2f03f7e3d920499564ed27 to your computer and use it in GitHub Desktop.
binarTree.cpp
This file contains 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> | |
#include <vector> | |
class BinaryList | |
{ | |
struct tree_node | |
{ | |
int value; | |
tree_node *left; | |
tree_node *right; | |
tree_node(int &&val = int()) | |
{ | |
left = right = nullptr; | |
value = std::forward<int>(val); | |
} | |
}; | |
public: | |
tree_node *m_root; | |
BinaryList() : m_root(nullptr) {} | |
void insertNode(int value) | |
{ | |
bool inserted = false; | |
if (m_root == nullptr) | |
{ | |
m_root = new tree_node(std::move(value)); | |
return; | |
} | |
tree_node *root = m_root; | |
while (!inserted) | |
{ | |
if (value <= root->value) | |
{ | |
if (root->left != nullptr) | |
root = root->left; | |
else | |
{ | |
root->left = new tree_node(std::move(value)); | |
inserted = true; | |
} | |
} | |
else | |
{ | |
if (root->right != nullptr) | |
root = root->right; | |
else | |
{ | |
root->right = new tree_node(std::move(value)); | |
inserted = true; | |
} | |
} | |
} | |
} | |
bool binarSearch(int value) | |
{ | |
tree_node *root = m_root; | |
while (true) | |
{ | |
if (root == nullptr) | |
{ | |
std::cout << "Not found" << std::endl; | |
return false; | |
} | |
else if (value == root->value) | |
{ | |
std::cout << "found data = " << root->value << std::endl; | |
return true; | |
} | |
else if (value < root->value) | |
{ | |
root = root->left; | |
} | |
else if (value > root->value) | |
{ | |
root = root->right; | |
} | |
} | |
} | |
}; | |
int main() | |
{ | |
srand(time(NULL)); | |
//const int n = 10; | |
BinaryList list; | |
list.insertNode(23); | |
list.insertNode(24); | |
list.insertNode(12); | |
list.insertNode(83); | |
/* | |
for (int i = 0; i < n; i++) | |
{ | |
int val = rand() % 77; | |
std::cout << val << " "; | |
list.insertNode(val); | |
}*/ | |
list.binarSearch(12); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment