肥肥翘班打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