2016 G面试题#2 不构造树的情况下验证先序遍历

时间:2023-03-09 16:58:27
2016 G面试题#2 不构造树的情况下验证先序遍历

2016 G面试题#2 不构造树的情况下验证先序遍历

 def isValidTree(POTra):
"""
POTra :param list:
:return:
""" if not POTra:
return True while len(POTra) > 1:
index = []
n = len(POTra)
for i in range(0, n-2):
if POTra[i] != '#' and POTra[i+1] == '#' and POTra[i+2] == '#':
POTra[i] = '#'
index.append(i+1)
index.append(i+2)
else:
continue
removeset = set(index)
POTra = [v for i, v in enumerate(POTra) if i not in removeset]
#print(POTra)
if len(POTra) == n:
break if POTra == ['#']:
return True
else:
return False

Keys: 在一个list中根据index可以同时去掉多个element, see L21