summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKohei Yoshida <kohei.yoshida@gmail.com>2012-07-08 16:14:41 -0400
committerKohei Yoshida <kohei.yoshida@gmail.com>2012-07-08 16:14:41 -0400
commitef2c9e51bc40ed2f1b47c25adf83756f71f3c8b7 (patch)
treea4d4d8987faabb66c4ea7226d35090770ff351ab
parentaf3e2da9b5b6b11b42e99c54fb914fd9505881f3 (diff)
Base framework for populating tree structure.
-rw-r--r--tree.cpp126
1 files changed, 126 insertions, 0 deletions
diff --git a/tree.cpp b/tree.cpp
new file mode 100644
index 0000000..690c964
--- /dev/null
+++ b/tree.cpp
@@ -0,0 +1,126 @@
+
+#include <cstdlib>
+#include <iostream>
+#include <string>
+#include <cassert>
+
+using namespace std;
+
+struct node
+{
+ node* left;
+ node* right;
+ long value;
+
+ node(long _value) : left(NULL), right(NULL), value(_value) {}
+};
+
+void clean_node(node* nd)
+{
+ if (!nd)
+ return;
+
+ clean_node(nd->left);
+ nd->left = NULL;
+ clean_node(nd->right);
+ nd->right = NULL;
+ delete nd;
+}
+
+void clean_tree(node* root)
+{
+ clean_node(root);
+}
+
+void print_node(node* nd)
+{
+ if (!nd)
+ return;
+
+ print_node(nd->left);
+ cout << nd->value << " ";
+ print_node(nd->right);
+}
+
+void print_tree(node* root)
+{
+ cout << "tree content: ";
+ print_node(root);
+ cout << endl;
+}
+
+void insert_value(node* root, long value)
+{
+ while (true)
+ {
+ assert(root);
+ if (root->value == value)
+ // duplicates are not allowed.
+ return;
+
+ if (value < root->value)
+ {
+ if (!root->left)
+ {
+ root->left = new node(value);
+ return;
+ }
+
+ root = root->left;
+ }
+ else
+ {
+ assert(value > root->value);
+ if (!root->right)
+ {
+ root->right = new node(value);
+ return;
+ }
+
+ root = root->right;
+ }
+ }
+}
+
+int main()
+{
+ node* root = NULL;
+ while (true)
+ {
+ string val;
+ cin >> val;
+
+ if (val.empty())
+ break;
+
+ if (val == "q" || val == "quit")
+ {
+ cout << "terminating" << endl;
+ break;
+ }
+
+ // End position on successful conversion.
+ const char* end_pos = val.c_str() + val.size();
+
+ char* end_ptr = NULL;
+ long lval = strtol(&val[0], &end_ptr, 10);
+ if (end_pos != end_ptr)
+ {
+ // String didn't get scanned in its entirety. Must have failed.
+ cerr << "invalid integer: " << val << endl;
+ continue;
+ }
+ cout << "input number: " << lval << endl;
+
+ if (!root)
+ root = new node(lval);
+ else
+ insert_value(root, lval);
+
+ print_tree(root);
+ }
+
+ clean_tree(root);
+
+ return EXIT_SUCCESS;
+}