aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--btree.cpp26
1 files changed, 26 insertions, 0 deletions
diff --git a/btree.cpp b/btree.cpp
index c22c297..0ac794f 100644
--- a/btree.cpp
+++ b/btree.cpp
@@ -24,3 +24,29 @@ struct BinaryTree
}
};
+template <typename T>
+BinaryTree<T> *insert(BinaryTree<T> *tree, T value)
+{
+ BinaryTree<T> **node = &tree;
+ switch (tree->compare(value, tree->value))
+ {
+ case LT:
+ node = &tree->left;
+ break;
+ case EQ:
+ case GT:
+ node = &tree->right;
+ break;
+ }
+
+ if (*node) {
+ *node = insert(*node, value);
+ return tree;
+ }
+ *node = new BinaryTree<T>;
+ (*node)->value = value;
+ (*node)->left = (*node)->right = nullptr;
+ (*node)->compare = tree->compare;
+ return tree;
+}
+