Trees
BST Search
Search a binary search tree for one present and one absent value.
Algorithm
Basic Implementation
basic.cpp
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct Node { int value; Node* left; Node* right; Node(int v, Node* l=nullptr, Node* r=nullptr): value(v), left(l), right(r) {} };
string render(Node* node) {
if (node == nullptr) return "_";
if (node->left == nullptr && node->right == nullptr) return to_string(node->value);
return to_string(node->value) + "(" + render(node->left) + "," + render(node->right) + ")";
}
Node* sampleTree() {
return new Node(4, new Node(2, new Node(1), new Node(3)), new Node(6, new Node(5), new Node(7)));
}
string listString(const vector<int>& values) {
stringstream out; out << "[";
for (size_t i = 0; i < values.size(); i++) { if (i) out << ", "; out << values[i]; }
out << "]"; return out.str();
}
bool search(Node* root, int target) { Node* node = root; while (node) { if (target == node->value) return true; node = target < node->value ? node->left : node->right; } return false; }
int main() { Node* root = sampleTree(); cout << (search(root, 5) ? "5 found" : "5 not found") << "\n"; cout << (search(root, 8) ? "8 found" : "8 not found") << "\n"; }
Complexity
- Time: O(h) per search
- Space: O(1) iterative
Implementation notes
- In C++, each tree node is a
struct Nodewithint valueand rawNode* left/Node* rightchild links defaulting tonullptr. sampleTree()allocates the canonical tree with nestednew Node(...)calls. The source uses raw pointers, not smart pointers, and does not show a matchingdeletecleanup path.search(Node* root, int target)is iterative:Node* node = rootis the cursor,while (node)is the null check, and each branch reassigns the cursor tonode->leftornode->right.- Comparisons are scalar
inttests. A match returnstrue; otherwisetarget < node->valuechooses left and theelsepath chooses right. - The trace shows search
5moving4 -> right,6 -> left, then matching5; search8moves4 -> right,6 -> right,7 -> right, then reachesnull. - Output is streamed as conditional string literals:
5 foundand8 not found. Search itself mutates only the local cursor; the tree links are read-only after allocation.
search path
A comparison chooses one subtree at each step, so whole branches are skipped.