肥肥翹班打code
先寫了稍微浪費一點點空間慢一點的版本
看到討論區標題之後 再寫了個好像快一點的版本
雖然複雜度都一樣就是
def createBinaryTree(self, descriptions: List[List[int]]) ->
Optional[TreeNode]:
g = defaultdict(lambda: [-1,-1])
childs = set()
for d in descriptions:
if d[2] == 1:
g[d[0]][0] = d[1]
else:
g[d[0]][1] = d[1]
childs.add(d[1])
root = -1
for node in g.keys():
if node not in childs:
root = node
break
def build(val) -> TreeNode:
if val == -1:
return None
return TreeNode(val, build(g[val][0]), build(g[val][1]))
return build(root)
def createBinaryTree(self, descriptions: List[List[int]]) ->
Optional[TreeNode]:
nodes = {}
childs = set()
for d in descriptions:
if d[0] not in nodes:
nodes[d[0]] = TreeNode(d[0])
if d[1] not in nodes:
nodes[d[1]] = TreeNode(d[1])
if d[2] == 1:
nodes[d[0]].left = nodes[d[1]]
else:
nodes[d[0]].right = nodes[d[1]]
childs.add(d[1])
for node in nodes.keys():
if node not in childs:
return nodes[node]
return None