DSA - Week 05 - 4 -Phone List

来源:互联网 发布:net域名怎么样 编辑:程序博客网 时间:2024/06/14 19:23
# include <iostream># include <string>using namespace std;class tree_node{public:char val;//to skip the type conversiontree_node* left_child;tree_node* right_sibling;tree_node(const char v = '\0', tree_node* l = NULL, tree_node* r = NULL ){val = v;left_child = l;right_sibling = r;}bool isleaf(){if ( left_child == NULL ){return true;}else return false;}};class tree{public:tree_node* root;//constructortree(tree_node* r = NULL){root = r;}//methodsbool insert_number(string& s){bool parent_tag = false;tree_node* curr = root;tree_node* prev = NULL;int len = s.length();for ( int i = 0; i < len; i++ ){//search rightward for the same digitwhile ( curr != NULL ){if ( s[i] == curr->val ){//if the new phone number is the suffix of an existing one, it is illegalif ( curr->isleaf() ){return false;}if ( i == len-1 )//if the phone number is the prefix of an existing one it is as well illegal{return false;}prev = curr;curr = curr->left_child;//move on to the next levelparent_tag = true;//prev represents the parent nodebreak;}else{prev = curr;curr = curr->right_sibling;parent_tag = false;}}if ( curr == NULL ){curr = new tree_node(s[i]);if ( root == NULL ){root = curr;}//if there are siblings on the left, the new node needed to be linked with its former siblingsif ( prev != NULL ){if ( parent_tag ){prev->left_child = curr;}else{prev->right_sibling = curr;}}prev = curr;curr = curr->left_child;//move on to the next levelparent_tag = true;}}return true;}};void check(){int n = 0;string input;bool consistent = true;tree t;cin >> n;//n linesfor ( int i = 0; i < n; i++ ){cin >> input;if ( !t.insert_number(input) ){consistent = false;}}if ( consistent ){cout << "YES" << endl;}else{cout << "NO" << endl;}}int main(){int t = 0;cin >> t;for ( int i = 0; i < t; i++ ){check();}return 0;}

原创粉丝点击