-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsolution.py
35 lines (29 loc) · 1001 Bytes
/
solution.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
class Solution:
def validateBinaryTreeNodes(self, n, leftChild, rightChild):
indegree = [0] * n
for i in range(n):
if leftChild[i] != -1:
indegree[leftChild[i]] += 1
if rightChild[i] != -1:
indegree[rightChild[i]] += 1
root = None
for i in range(n):
if indegree[i] == 0:
if root is None:
root = i
else:
return False
if root is None:
return False
visited = [False] * n
queue = deque([root])
while queue:
node = queue.popleft()
if visited[node]:
return False
visited[node] = True
if leftChild[node] != -1:
queue.append(leftChild[node])
if rightChild[node] != -1:
queue.append(rightChild[node])
return sum(visited) == n