#include #include #include #include struct node { string data; node * left, * right; node(string s, node * L, node * R); }; node::node(string s, node * L = NULL, node * R = NULL) { data = s; left = L; right = R; } struct tree { node * root; tree(); void insert(string s); void insert(string s, node * & ptr); void print(); void print(node * ptr, string path); node * readtree(); void read(); }; tree::tree() { root = NULL; } void tree::insert(string s) { insert(s, root); } void tree::insert(string s, node * & ptr) { if (ptr == NULL) ptr = new node(s); else if (s < ptr->data) insert(s, ptr->left); else insert(s, ptr->right); } void tree::print() { print(root, ""); } string convert(string s) { string result = ""; int len = s.length(); if (len == 0) return result; for (int i = 0; i < len-1; i += 1) { if (s[i] == s[i+1]) result += " "; else result += "| "; } result += "+--"; return result; } void tree::print(node * ptr, string path) { if (ptr != NULL) { print(ptr->left, path+"L"); cout << convert(path) << ptr->data << "\n"; print(ptr->right, path+"R"); } } char get_next_char() { while (true) { char c = getchar(); if (c != ' ') return c; } } void pretend_you_didnt_read(char c) { ungetc(c, stdin); } string readstring() { string r = ""; while (true) { char c = get_next_char(); if (c < 'a' || c > 'z') { pretend_you_didnt_read(c); return r; } r += c; } } node * tree::readtree() { char c = get_next_char(); if (c == '.') return NULL; node * left_subtree = readtree(); string here_data = readstring(); node * right_subtree = readtree(); c = get_next_char(); if (c != ')') cout << "\nerror\n"; return new node(here_data, left_subtree, right_subtree); } void tree::read() { root = readtree(); char c = get_next_char(); if (c != '\n') cout << "\nerror\n"; } void main() { tree T; while (true) { cout << "? "; T.read(); T.print(); cout << "\n\n"; } }