forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate Binary Tree Nodes.py
50 lines (32 loc) · 1.13 KB
/
Validate Binary Tree Nodes.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
40
41
42
43
44
45
46
47
48
49
50
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
left_set=set(leftChild)
right_set=set(rightChild)
que=[]
for i in range(n):
if i not in left_set and i not in right_set:
que.append(i)
if len(que)>1 or len(que)==0:
return False
graph=defaultdict(list)
for i in range(n):
graph[i]=[]
if leftChild[i]!=-1:
graph[i].append(leftChild[i])
if rightChild[i]!=-1:
graph[i].append(rightChild[i])
visited=set()
visited.add(que[0])
while len(que)>0:
item=que.pop(0)
children=graph[item]
for child in children:
if child not in visited:
que.append(child)
visited.add(child)
else:
return False
for i in range(n):
if i not in visited:
return False
return True