# include <iostream>
# include <string>
using namespace std;
class tree_node{
public:
char val; //to skip the type conversion
tree_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;
//constructor
tree(tree_node* r = NULL)
{
root = r;
}
//methods
bool 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 digit
while ( curr != NULL )
{
if ( s[i] == curr->val )
{
//if the new phone number is the suffix of an existing one, it is illegal
if ( 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 level
parent_tag = true; //prev represents the parent node
break;
}
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 siblings
if ( 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 level
parent_tag = true;
}
}
return true;
}
};
void check()
{
int n = 0;
string input;
bool consistent = true;
tree t;
cin >> n; //n lines
for ( 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;
}
DSA - Week 05 - 4 -Phone List
最新推荐文章于 2020-09-15 18:56:16 发布