Advertisement
TwentyEight

81N4RY TR33

Feb 26th, 2020
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. import numpy as np
  2. class Solution:
  3.     def __init__(self):
  4.         self.visited = [] # label visited nodes (and if nodes are visited again then graph is cyclic)
  5.        
  6.     def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
  7.         self.visited = np.array([0]*n)
  8.         isTree = self.visitNode(leftChild, rightChild, 0)
  9.         if (isTree == False) or len(set(self.visited)) > 1: # if cyclic then isTree is false; if visited has 0s and 1s then not all nodes visited (thus there may be more than one tree)
  10.             return False
  11.         return True
  12.        
  13.     def visitNode(self, leftChild, rightChild, node):
  14.         if self.visited[node] == 0:
  15.             self.visited[node] = 1
  16.         else:
  17.             return False # node has been visited already (graph is cyclic and thus not a tree)
  18.         isTree = True
  19.         if leftChild[node] != -1: # check if there is left child
  20.             isTree = self.visitNode(leftChild, rightChild, leftChild[node]) # now visit left child node (recursive)
  21.         if rightChild[node] != -1: # check if there is right child
  22.             isTree = isTree and self.visitNode(leftChild, rightChild, rightChild[node]) # now visit right child node (recursive)
  23.         return isTree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement