-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_constructor.py
More file actions
29 lines (21 loc) · 900 Bytes
/
Copy pathtree_constructor.py
File metadata and controls
29 lines (21 loc) · 900 Bytes
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
def tree_constructor(strArr) -> bool:
parents = {}
children = {}
for pair in strArr:
child, parent = pair.replace("(", "").replace(")", "").split(",")
if parent not in parents:
parents[parent] = []
parents[parent].append(child)
# Check if the parent has more than 2 children (invalid binary tree)
if len(parents[parent]) > 2:
return False
# Check if the child already has a parent (invalid binary tree)
if child in children:
return False
children[child] = parent
rootCount = len(list(filter(lambda parent: all(child not in parents for child in parents[parent]), parents)))
# for parent in parents:
# if parent not in children:
# rootCount += 1
# There should be exactly one root for a valid binary tree
return rootCount == 1