-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-search-tree.cpp
More file actions
100 lines (91 loc) · 2.07 KB
/
binary-search-tree.cpp
File metadata and controls
100 lines (91 loc) · 2.07 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
/**
* @file binary-search-tree.cpp
* @author nirmeet baweja
* @brief Binary search tree (BST) is a binary tree where the value of each
* node is larger or equal to the values in all the nodes in that node's left
* subtree and is smaller than the values in all the nodes in that node's right
* subtree.
* Write a function that, efficiently with respect to time used, checks if a
* given binary search tree contains a given value.
* For example, for the following tree:
* n1 (Value: 1, Left: null, Right: null)
* n2 (Value: 2, Left: n1, Right: n3)
* n3 (Value: 3, Left: null, Right: null)
* Call to contains(n2, 3)
* should return true since a tree with root at n2 contains number 3.
*
* @version 0.1
* @date 2022-02-02
*
* @copyright Copyright (c) 2022
*
*/
#include <stdexcept>
#include <string>
#include <iostream>
class Node
{
public:
Node(int value, Node *left, Node *right)
{
this->value = value;
this->left = left;
this->right = right;
}
int getValue() const
{
return value;
}
Node *getLeft() const
{
return left;
}
Node *getRight() const
{
return right;
}
private:
int value;
Node *left;
Node *right;
};
class BinarySearchTree
{
public:
static bool contains(const Node &root, int value)
{
int node_value = root.getValue();
if (node_value == value)
{
return true;
}
else if (node_value < value)
{
Node *right = root.getRight();
if (right == NULL)
{
return false;
}
return contains(*right, value);
}
else
{
Node *left = root.getLeft();
if (left == NULL)
{
return false;
}
return contains(*left, value);
}
}
};
#ifndef RunTests
int main()
{
std::cout << "Binary Search.\n";
Node n1(1, NULL, NULL);
Node n3(3, NULL, NULL);
Node n2(2, &n1, &n3);
std::cout << BinarySearchTree::contains(n2, 3);
}
#endif