DSA - Week 05 - 4 -Phone List

# 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值