🏌🏻‍♂️TreeQuery-HUAWEI-CodingInterview⏯️

16
Aug 14, 2023
Aug 23, 2023

Topic

22-TreeQuery-HUAWEI-CodingInterview

Key Point & Tag

KeyValue
Difficulty AssessmentEasy
Tag
Similar Problem

Code

class TreeQuery:
	# Input Part
	def GetInput(self)->None:
		'''
		Get Input Data and Preprocess Data
		'''
		self.N = int(input()) 
		mat = [list(map(str, input().split())) for _ in range(self.N)]
		self.K = input().strip() # Query Key Words
		
		# mat = [	['b', 'a'],
		# 		['c', 'a'],
		# 		['d', 'c'],
		# 		['e', 'c'],
		# 		['f', 'd']]
		# self.K = 'c' # Query Key Words

		self.dic = {} # {k1:[v1, v2]}
		for v, k in mat:
			self.dic[k] = self.dic.get(k, set()) | {v} # Union Two Set

	# Algorithm Part
	def Solution(self)->int:
		'''
		Algorithm Solving Problem
		'''
		# Get data from self
		K = self.K
		dic = self.dic

		res = [x for x in dic[K]] # each elem
		i = 0
		while i < len(res):
			# res.append(q[i])
			if dic.get(res[i], None):
				res += [x for x in dic[res[i]]]
			i += 1
		
		res.sort() # ASC Sort by Lexicographical Order
		return '\n'.join(res)

# Execution Part
if __name__ == "__main__":
	# Instantiate
	obj = TreeQuery()
	# Get Input
	obj.GetInput()
	# Get Result
	print(obj.Solution())

Test Cases

5
b a
c a
d c
e c
f d
c
Comments (0)