給出一顆二叉樹節(jié)點(diǎn)數(shù)量和每個(gè)節(jié)點(diǎn)的左兒子label集合以及右兒子label集合,問是否是一顆二叉樹,先用set選出root然后BFS,如果同一個(gè)節(jié)點(diǎn)訪問不止一次或者有節(jié)點(diǎn)訪問不到,則不是二叉樹
1 #1361
2 #Runtime: 224 ms (Beats 92.11%)
3 #Memory: 15.5 MB (Beats 71.5%)
4
5 class Solution(object):
6 def validateBinaryTreeNodes(self, n, leftChild, rightChild):
7 """
8 :type n: int
9 :type leftChild: List[int]
10 :type rightChild: List[int]
11 :rtype: bool
12 """
13 rt = 0
14 child_nodes = set(leftChild + rightChild)
15 for i in xrange(n):
16 if i not in child_nodes:
17 rt = i
18 vis = set()
19 q = deque([rt])
20 while q:
21 node = q.popleft()
22 if node in vis:
23 return False
24 vis.add(node)
25 if leftChild[node] != -1:
26 q.append(leftChild[node])
27 if rightChild[node] != -1:
28 q.append(rightChild[node])
29 return len(vis) == n