summaryrefslogtreecommitdiff
path: root/algorithms/binary_tree.cc
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2014-06-15 03:24:33 +0200
committerPatrick Simianer <p@simianer.de>2014-06-15 03:24:33 +0200
commitcf3a29feb5887344b6633ead1b4b6d5657a15a4b (patch)
treef1149508f7305a48dba0226699dfafdd68d81969 /algorithms/binary_tree.cc
parent5ddc763ab9953eebdaf78af4eb72288d7955b310 (diff)
old stuff: algorithms
Diffstat (limited to 'algorithms/binary_tree.cc')
-rw-r--r--algorithms/binary_tree.cc118
1 files changed, 118 insertions, 0 deletions
diff --git a/algorithms/binary_tree.cc b/algorithms/binary_tree.cc
new file mode 100644
index 0000000..d912aec
--- /dev/null
+++ b/algorithms/binary_tree.cc
@@ -0,0 +1,118 @@
+#include <iostream>
+
+using std::cout;
+using std::endl;
+
+
+struct Node {
+ int value;
+ Node* pLeft;
+ Node* pRight;
+};
+
+struct Tree {
+ Node* pRoot;
+};
+
+Node*
+new_node(int value)
+{
+ Node* node = new Node;
+ node->value = value;
+ node->pLeft = node->pRight = NULL;
+ return node;
+}
+
+void
+delete_node(Node* pNode)
+{
+ if(pNode->pLeft)
+ delete pNode->pLeft;
+ if(pNode->pRight)
+ delete pNode->pRight;
+ delete pNode;
+}
+
+void
+insert_node(Node* n, Node* i)
+{
+ if(i->value <= n->value) {
+ if(n->pLeft) {
+ insert_node(n->pLeft, i);
+ } else {
+ n->pLeft = i;
+ }
+ } else {
+ if(n->pRight) {
+ insert_node(n->pRight, i);
+ } else {
+ n->pRight = i;
+ }
+ }
+}
+
+void
+insert(Tree& tree, int value)
+{
+ Node *n = new_node(value);
+
+ if(!tree.pRoot) {
+ tree.pRoot = n;
+ } else {
+ if(n->value <= tree.pRoot->value) {
+ if(tree.pRoot->pLeft) {
+ insert_node(tree.pRoot->pLeft, n);
+ } else {
+ tree.pRoot->pLeft = n;
+ }
+ } else {
+ if(tree.pRoot->pRight) {
+ insert_node(tree.pRoot->pRight, n);
+ } else {
+ tree.pRoot->pRight = n;
+ }
+ }
+ }
+}
+
+void
+print_nodes_inorder(Node *n)
+{
+ if(n->pLeft) {
+ print_nodes_inorder(n->pLeft);
+ }
+
+ cout << n->value << endl;
+
+ if(n->pRight) {
+ print_nodes_inorder(n->pRight);
+ }
+}
+
+void
+print_sorted(Tree& tree)
+{
+ Node *n=tree.pRoot;
+
+ print_nodes_inorder(n);
+}
+
+int
+main()
+{
+ Tree tree;
+ tree.pRoot = NULL;
+
+ int feld[10] = {8, 12, 5, 24, 2, 6, 98, 67, 1, 6};
+
+ for(int i = 0; i < 10; ++i)
+ insert(tree, feld[i]);
+
+ print_sorted(tree);
+
+ if(tree.pRoot)
+ delete_node(tree.pRoot);
+
+ return 0;
+}
+