-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeSort.cpp
101 lines (85 loc) · 1.98 KB
/
BinaryTreeSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <memory>
class BinaryTree
{
public:
using Visitor = std::function<void(int)>;
private:
struct Node
{
std::shared_ptr<Node> left, right;
int value;
};
std::shared_ptr<Node> root;
private:
void insert_recursive(const std::shared_ptr<Node>& cur, const std::shared_ptr<Node>& insert)
{
bool insertIsLess = insert->value < cur->value;
if(insertIsLess)
{
// в левое
if(cur->left == nullptr)
cur->left = insert;
else
insert_recursive(cur->left, insert);
}
else
{
// в правое
if(cur->right == nullptr)
cur->right = insert;
else
insert_recursive(cur->right, insert);
}
}
void visit_recursive(const std::shared_ptr<Node>& node, const Visitor& visitor)
{
// в левое
if(node->left != nullptr)
visit_recursive(node->left, visitor);
visitor(node->value);
// в правое
if(node->right != nullptr)
visit_recursive(node->right, visitor);
}
public:
void insert(int value)
{
std::shared_ptr<Node> insert = std::make_shared<Node>();
insert->value = value;
if(root == nullptr)
{
root = insert;
return;
}
insert_recursive(root, insert);
}
void visit(Visitor call)
{
if(root == nullptr)
return;
visit_recursive(root, call);
}
};
void BinaryTreeSort(std::vector<int>& items)
{
BinaryTree tree;
for(const auto item: items)
{
tree.insert(item);
}
tree.visit([](int value)
{
std::cout << value << ",";
});
std::cout << "\n";
}
int main()
{
std::vector<int> items {10, 25, 13, 6, 52, 1};
BinaryTreeSort(items);
return 0;
}