Last active
August 29, 2015 14:08
-
-
Save tanitanin/e61003c9e19e9f36e0c5 to your computer and use it in GitHub Desktop.
Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <list> | |
template<class T> | |
class BST { | |
public: | |
struct Node { | |
T value; | |
Node *lhs, *rhs, *parent; | |
bool operator<(Node &a) { return value < a.value; } | |
bool operator==(Node &a) { return value == a.value; } | |
}; | |
public: | |
explicit BST() { Node n; data.push_back(n); } | |
~BST() {} | |
Node *root() { return &data.front(); } | |
Node *add(T child, Node *parent=nullptr, bool right=true) { | |
Node n; n.value = child; n.lhs = n.rhs = nullptr; | |
data.push_back(n); | |
auto *ptr = &data.back(); | |
if(parent) { (right?parent->rhs:parent->lhs)=ptr; ptr->parent = parent; } | |
else { | |
auto *p = root(); | |
while(true) { | |
if(ptr->value < p->value) { | |
if(p->rhs == nullptr) { p->rhs = ptr; break; } | |
p = p->rhs; | |
} else { | |
if(p->lhs == nullptr) { p->lhs = ptr; break; } | |
p = p->lhs; | |
} | |
} | |
} | |
return ptr; | |
} | |
Node *search(T q) { | |
auto *ptr = root(); | |
while(ptr!=nullptr) { | |
if(ptr->value==q) return ptr; | |
ptr = (q < ptr->value ? ptr->rhs : ptr->lhs); | |
} | |
return ptr; | |
} | |
private: | |
std::list<Node> data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment