From ef2c9e51bc40ed2f1b47c25adf83756f71f3c8b7 Mon Sep 17 00:00:00 2001 From: Kohei Yoshida Date: Sun, 8 Jul 2012 16:14:41 -0400 Subject: Base framework for populating tree structure. --- tree.cpp | 126 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 tree.cpp 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 +#include +#include +#include + +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; +} -- cgit v1.2.3