-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadOnlyIntBinaryTree.cpp
More file actions
109 lines (99 loc) · 2.51 KB
/
ReadOnlyIntBinaryTree.cpp
File metadata and controls
109 lines (99 loc) · 2.51 KB
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
102
103
104
105
106
107
108
109
#include "ReadOnlyIntBinaryTree.h"
#include "assert.h"
using namespace readonly_int_binary_tree;
ReadOnlyIntBinaryTree::ReadOnlyIntBinaryTree()
{
root = nullptr;
}
ReadOnlyIntBinaryTree::~ReadOnlyIntBinaryTree()
{
DestoryTree();
}
// Public version of insert to handle case of root being
// null or call recursive version.
void ReadOnlyIntBinaryTree::Insert(int key)
{
if (root != nullptr)
Insert(key, root);
else
{
root = new Node;
root->key_value = key;
root->left = nullptr;
root->right = nullptr;
}
}
void ReadOnlyIntBinaryTree::Insert(int key, Node *node)
{
// Check if the key belongs on the left or right
// side of the current node.
if (key < node->key_value)
{
// If this node already has a child continue
// recursively searching to the left.
// Otherwise create a new left child node.
if (node->left != nullptr)
Insert(key, node->left);
else
{
node->left = new Node();
node->left->key_value = key;
node->left->left = nullptr;
node->left->right = nullptr;
}
}
// If this node already has a right child continue
// to recursively search to the right.
// Otherwise create a new right child node.
else if (key >= node->key_value)
{
if (node->right != nullptr)
Insert(key, node->right);
else
{
node->right = new Node();
node->right->key_value = key;
node->right->left = nullptr;
node->right->right = nullptr;
}
}
}
// Public version of Search to call recursive version.
Node *ReadOnlyIntBinaryTree::Search(int key)
{
return Search(key, root);
}
// Recursively searches down the tree until it either finds
// a node with a value that matches the key or it reaches
// the bottom of the tree (uninitialized node) which means
// the key being searched for does not exist in the tree.
Node *ReadOnlyIntBinaryTree::Search(int key, Node *node)
{
if (node != nullptr)
{
if (key == node->key_value)
return node;
if (key < node->key_value)
return Search(key, node->left);
else
return Search(key, node->right);
}
return nullptr;
}
// Public version of DestroyTree to call recursive version.
void ReadOnlyIntBinaryTree::DestoryTree()
{
DestoryTree(root);
root = nullptr;
}
// Recursively searches to the bottom of the tree (node is null)
// and then works its way back up deleting nodes as it goes.
void ReadOnlyIntBinaryTree::DestoryTree(Node *node)
{
if (node != nullptr)
{
DestoryTree(node->left);
DestoryTree(node->right);
delete node;
}
}