Commit 94acd25b authored by KTKadyshev's avatar KTKadyshev
Browse files

Upload New File

parent 851f370a
#include <iostream>
class Node
{
public:
Node(int value) {
this->value = value;
left = NULL;
right = NULL;
}
int value;
Node* left;
Node* right;
};
typedef void (*NodeFunction)(Node*);
class BTree
{
public:
Node* root;
BTree(int value) {
root = new Node(value);
}
~BTree() {
deleteLeftRight(root);
}
private:
static void deleteNode(Node* node) {
delete node;
}
void deleteLeftRight(Node* node) {
walkLR(deleteNode);
root = NULL;
}
public:
void add(int value) {
addTo(root, value);
}
private:
bool isRight(Node* node, int value) {
return value > node->value;
}
void addTo(Node* node, int value) {
bool right = isRight(node, value);
if (right) {
if (node->right == NULL) {
node->right = new Node(value);
}
else {
addTo(node->right, value);
}
}
else {
if (node->left == NULL) {
node->left = new Node(value);
}
else {
addTo(node->left, value);
}
}
}
public:
Node* find(int value) {
return findIn(root, value);
}
private:
Node* findIn(Node* node, int value) {
if (node == NULL)
return NULL;
if (node->value == value)
return node;
bool right = isRight(node, value);
if (right)
return findIn(node->right, value);
else
return findIn(node->left, value);
}
public:
void walkLR(NodeFunction f) {
walkToLR(root, f);
}
void walkRL(NodeFunction f) {
walkToRL(root, f);
}
void walkUD(NodeFunction f) {
walkToUD(root, f);
}
private:
void walkToLR(Node* node, NodeFunction f) {
if (node != NULL) {
walkToLR(node->left, f);
walkToLR(node->right, f);
f(node);
}
}
void walkToRL(Node* node, NodeFunction f) {
if (node != NULL) {
walkToRL(node->right, f);
walkToRL(node->left, f);
f(node);
}
}
void walkToUD(Node* node, NodeFunction f) {
if (node != NULL) {
f(node);
walkToRL(node->left, f);
walkToRL(node->right, f);
}
}
};
void PrintNode(Node* node) {
if (node != NULL) {
std::cout << node->value << " ";
}
}
int main()
{
BTree* tree = new BTree(8);
tree->add(5);
tree->add(7);
tree->add(12);
tree->add(3);
tree->add(2);
Node* n = tree->find(12);
std::cout << n->value << std::endl;
tree->walkUD(PrintNode);
delete tree;
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment