# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
isRoot = {} # 数值对应的节点是否为根节点的哈希表
nodes = {} # 数值与对应节点的哈希表
for p, c, left in descriptions:
if p not in isRoot:
isRoot[p] = True
isRoot[c] = False
# 创建或更新节点
if p not in nodes:
nodes[p] = TreeNode(p)
if c not in nodes:
nodes[c] = TreeNode(c)
if left:
nodes[p].left = nodes[c]
else:
nodes[p].right = nodes[c]
# 寻找根节点
root = -1
for val, r in isRoot.items():
if r:
root = val
break
return nodes[root]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 哈希表,建树,找根
class Solution:
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
nodes = defaultdict(TreeNode)
vals = set()
for x, y, left in descriptions:
if left:
nodes[x].left = nodes[y]
else:
nodes[x].right = nodes[y]
vals.add(y)
for v, node in nodes.items():
node.val = v
return next(node for v, node in nodes.items() if v not in vals)