#include #include using namespace std; struct Node { char label; int height; Node * left; Node * right; Node(char l, int h) : label(l), height(h), left(0), right(0) {} ~Node() { delete left; delete right; } int getHeight() { if (!left && !right) return height; int l = -1; int r = -1; if (left) l = left->getHeight(); if (right) r = right->getHeight(); if (l > r) return l; else return r; } bool isBalanced() { bool result = true; if (left) result = left->isBalanced(); if (!result) return false; if (right) result = right->isBalanced(); if (!result) return false; int leftHeight = 0; int rightHeight = 0; if (left) leftHeight = left->getHeight() - height; if (right) rightHeight = right->getHeight() - height; if (leftHeight - rightHeight <= 1 && leftHeight - rightHeight >= -1) { return true; } else return false; } bool isBST() { if (!left && !right) return true; if (left && left->label > label) return false; if (right && right->label < label) return false; bool result = true; if (left) result = left->isBST(); if (!result) return false; if (right) result = right->isBST(); return result; } void print() { if (left) { cout << "("; left->print(); cout << ")"; } cout << label; if (right) { cout << "("; right->print(); cout << ")"; } } }; string stripChunk(string & s) { string result = ""; if (s[0] == '(') { int index = 1; int depth = 1; while (depth && index < s.length()) { if (s[index] == ')') { if (depth > 1) result += s[index]; index++; depth--; } else { if (s[index] == '(') depth++; result += s[index]; index++; } } string leftover = ""; if (index < s.length()) leftover = s.substr(index, s.length() - index); s = leftover; } else { result += s[0]; s = s.substr(1, s.length() - 1); } return result; } Node * parseTree(string & source, int depth) { if (source[0] != '(') { Node * result = new Node(source[0], depth); if (source.length() > 1) source = source.substr(1, source.length()-1); return result; } else { string temp = stripChunk(source); Node * left = 0; Node * right = 0; if (temp != "") left = parseTree(temp, depth+1); temp = stripChunk(source); Node * result = new Node(temp[0], depth); temp = stripChunk(source); if (temp != "") right = parseTree(temp, depth+1); result->left = left; result->right = right; return result; } } int main() { int cases; cin >> cases; for (int i = 0; i < cases; i++) { string treeDesc = ""; cin >> treeDesc; Node * tree = parseTree(treeDesc, 0); cout << "Tree #" << i+1; bool isBalanced = tree->isBalanced(); bool isBST = tree->isBST(); if (isBalanced && isBST) cout << " is an AVL Tree." << endl; else if (isBST) cout << " is a binary search tree." << endl; else cout << " is just an ordinary tree." << endl; } }