Skip to content

Instantly share code, notes, and snippets.

@CrazyPython CrazyPython/main.cpp Secret
Created Jun 7, 2016

Embed
What would you like to do?
codez
#include <iostream>
using namespace std;
struct Node {
int key;
Node *leftnode;
Node *rightnode;
string value;
Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {}
};
Node root_node(1, "Node #1"); // Binary search tree
string inline query_bst(const int key) {
Node *cur_node = &root_node;
while (cur_node != NULL) {
if (key == cur_node->key) {
return cur_node->value;
}
if (key < cur_node->key) { /* value already returned, no need for else */
cur_node = cur_node->leftnode;
} else {
cur_node = cur_node->rightnode;
}
}
return ""; // Return empty string if not found
}
void inline insert_bst(int key, string value) {
Node *cur_node;
Node *next_node = &root_node;
// Search through bst for key
while (next_node != NULL) {
cur_node = next_node;
if (key < cur_node->key) {
next_node = cur_node->leftnode;
} else {
next_node = cur_node->rightnode;
}
}
Node new_node(key, value);
next_node = &new_node;
if (key < cur_node->key) {
cur_node->leftnode = next_node;
} else {
cur_node->rightnode = next_node;
}
}
int main() {
root_node.key = 1;
insert_bst(2, "Node #3");
insert_bst(3, "Node #4");
cout << query_bst(3) << '\n' << query_bst(4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.