26 lines
881 B
Python
26 lines
881 B
Python
# https://leetcode.com/problems/create-binary-tree-from-descriptions
|
|
from typing import Dict, List, Optional
|
|
|
|
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: Dict[int, TreeNode] = {}
|
|
s = set()
|
|
for head, next, left in descriptions:
|
|
if nodes.get(head) is None:
|
|
nodes[head] = TreeNode(head)
|
|
if nodes.get(next) is None:
|
|
nodes[next] = TreeNode(next)
|
|
if left:
|
|
nodes[head].left = nodes[next]
|
|
else:
|
|
nodes[head].right = nodes[next]
|
|
s.add(next)
|
|
for node in nodes:
|
|
if node not in s:
|
|
return nodes[node]
|
|
|