phatboislym

Untitled

Jul 15th, 2024
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | Source Code | 0 0
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. #     def __init__(self, val=0, left=None, right=None):
  4. #         self.val = val
  5. #         self.left = left
  6. #         self.right = right
  7. class Solution:
  8.     def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
  9.         graph = {}
  10.         children = set()
  11.        
  12.         def build(root: Optional[TreeNode]) -> None:
  13.             children = graph.get(root.val)
  14.            
  15.             if children:
  16.                 for child, flag in children:
  17.                     if flag:
  18.                         root.left = TreeNode(child)
  19.                     else:
  20.                         root.right = TreeNode(child)
  21.  
  22.                 if root.left:
  23.                     build(root.left)
  24.                 if root.right:
  25.                     build(root.right)
  26.  
  27.         for parent, child, flag in descriptions:
  28.             if parent in graph:
  29.                 graph[parent].append((child, flag))
  30.             else:
  31.                 graph[parent] = [(child, flag)]
  32.             children.add(child)
  33.        
  34.         root = None
  35.        
  36.         for parent, _, _ in descriptions:
  37.             if parent not in children:
  38.                 root = parent
  39.        
  40.         head = TreeNode(root)
  41.         build(head)
  42.        
  43.         return head
Advertisement
Add Comment
Please, Sign In to add comment