Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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]:
- graph = {}
- children = set()
- def build(root: Optional[TreeNode]) -> None:
- children = graph.get(root.val)
- if children:
- for child, flag in children:
- if flag:
- root.left = TreeNode(child)
- else:
- root.right = TreeNode(child)
- if root.left:
- build(root.left)
- if root.right:
- build(root.right)
- for parent, child, flag in descriptions:
- if parent in graph:
- graph[parent].append((child, flag))
- else:
- graph[parent] = [(child, flag)]
- children.add(child)
- root = None
- for parent, _, _ in descriptions:
- if parent not in children:
- root = parent
- head = TreeNode(root)
- build(head)
- return head
Advertisement
Add Comment
Please, Sign In to add comment