forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(LEETCODE) CreateBinaryTreeFromDescriptions.py
34 lines (34 loc) · 1.13 KB
/
(LEETCODE) CreateBinaryTreeFromDescriptions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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 = {}
children = set()
vertices = set()
for description in descriptions:
parentVal = description[0]
childVal = description[1]
isLeft = description[2]
vertices.add(parentVal)
vertices.add(childVal)
children.add(childVal)
if parentVal in nodes:
parent = nodes[parentVal]
else:
parent = TreeNode(parentVal)
if childVal in nodes:
child = nodes[childVal]
else:
child = TreeNode(childVal)
if isLeft:
parent.left = child
else:
parent.right = child
nodes[parentVal] = parent
nodes[childVal] = child
root = list(vertices - children)[0]
return nodes[root]