-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJul-15-24.py
39 lines (34 loc) · 1.14 KB
/
Jul-15-24.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
35
36
37
38
39
# 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 __init__(self):
self.d = defaultdict(dict)
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
def buildTree(root):
if 'l' in self.d[root.val]:
root.left = buildTree(TreeNode(self.d[root.val]['l']))
if 'r' in self.d[root.val]:
root.right = buildTree(TreeNode(self.d[root.val]['r']))
return root
# parent->child mapping
for i in descriptions:
if i[2]==1:
self.d[i[0]]['l'] = i[1]
else:
self.d[i[0]]['r'] = i[1]
# fiding root
parents = set()
for i in descriptions:
parents.add(i[0])
for i in descriptions:
if i[1] in parents:
parents.remove(i[1])
for i in parents:
p = i
# building B-tree
root = buildTree(TreeNode(p))
return root