-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfull_binary_tree.hpp
64 lines (54 loc) · 1.75 KB
/
full_binary_tree.hpp
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
#pragma once
#include "common.hpp"
template <typename NodeData, typename LeafData>
class FullBinaryTree {
public:
typedef FullBinaryTree<NodeData, LeafData> Self;
struct Node : public NodeData {
FullBinaryTree<NodeData, LeafData> left;
FullBinaryTree<NodeData, LeafData> right;
Node(
NodeData nodeData,
FullBinaryTree<NodeData, LeafData> left,
FullBinaryTree<NodeData, LeafData> right
)
: NodeData(move(nodeData)),
left(move(left)),
right(move(right))
{ }
};
typedef LeafData Leaf;
FullBinaryTree() { }
FullBinaryTree(NodeData nodeData, Self left, Self right)
: tree_(make_unique<variant<Node, Leaf>>(Node(move(nodeData), move(left), move(right))))
{ }
FullBinaryTree(LeafData leafData)
: tree_(make_unique<variant<Node, Leaf>>(Leaf(move(leafData))))
{ }
template <typename NodeVisitor, typename LeafVisitor>
auto visit(NodeVisitor nodeVisitor, LeafVisitor leafVisitor) const {
assert(tree_);
return lambdaVisit(*tree_,
[&](const Node& node) {
return nodeVisitor(node);
},
[&](const Leaf& node) {
return leafVisitor(node);
}
);
}
template <typename NodeVisitor, typename LeafVisitor>
auto visit(NodeVisitor nodeVisitor, LeafVisitor leafVisitor) {
assert(tree_);
return lambdaVisit(*tree_,
[&](Node& node) {
return nodeVisitor(node);
},
[&](Leaf& node) {
return leafVisitor(node);
}
);
}
private:
unique_ptr<variant<Node, Leaf>> tree_;
};