-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.cpp
54 lines (46 loc) · 1.25 KB
/
binary_tree.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
#include "binary_tree.h"
BinaryTree::BinaryTree() : root(nullptr) {
}
BinaryTree::~BinaryTree() = default;
void BinaryTree::add(int value) {
add(value, root);
}
void BinaryTree::add(int value, std::unique_ptr<Node> &node) {
if (!node) {
node = std::make_unique<Node>(value);
} else if (value < node->value) {
add(value, node->left);
} else if (value > node->value) {
add(value, node->right);
} else {
// Value already exists; do nothing or handle duplicates
}
}
bool BinaryTree::contains(int value) const {
return contains(value, root);
}
bool BinaryTree::contains(int value, const std::unique_ptr<Node> &node) const {
if (!node) {
return false;
}
if (node->value == value) {
return true;
}
if (value < node->value) {
return contains(value, node->left);
}
return contains(value, node->right);
}
bool operator==(const BinaryTree &t1, const BinaryTree &t2) {
return BinaryTree::isIdentical(t1.root, t2.root);
}
bool BinaryTree::isIdentical(const std::unique_ptr<Node> &a,
const std::unique_ptr<Node> &b) {
if (!a && !b) {
return true;
}
if (a && b && a->value == b->value) {
return isIdentical(a->left, b->left) && isIdentical(a->right, b->right);
}
return false;
}