#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; } } } bool count_depth(const node* nd, int& depth) { assert(nd); int d_left = 0; int d_right = 0; if (nd->left) { if (!count_depth(nd->left, d_left)) return false; } if (nd->right) { if (!count_depth(nd->right, d_right)) return false; } cout << "(" << nd->value << ") left:" << d_left << " right:" << d_right << endl; if (d_left > d_right && d_left-d_right > 1) return false; if (d_right > d_left && d_right-d_left > 1) return false; depth += 1 + (d_left > d_right ? d_left : d_right); return true; } void check_balance(const node* root) { cout << "checking the balance of the tree..." << endl; if (!root) return; int depth = -1; bool res = count_depth(root, depth); if (res) cout << "tree is balanced (depth: " << depth << ")" << endl; else cout << "tree is not balanced" << endl; } int main() { node* root = NULL; while (true) { cout << "> "; string val; cin >> val; if (val.empty()) break; if (val == "q" || val == "quit") { cout << "terminating" << endl; break; } if (val == "c" || val == "check") { check_balance(root); continue; } // 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; }