Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- class Solution:
- def __init__(self):
- self.visited = [] # label visited nodes (and if nodes are visited again then graph is cyclic)
- def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
- self.visited = np.array([0]*n)
- isTree = self.visitNode(leftChild, rightChild, 0)
- 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)
- return False
- return True
- def visitNode(self, leftChild, rightChild, node):
- if self.visited[node] == 0:
- self.visited[node] = 1
- else:
- return False # node has been visited already (graph is cyclic and thus not a tree)
- isTree = True
- if leftChild[node] != -1: # check if there is left child
- isTree = self.visitNode(leftChild, rightChild, leftChild[node]) # now visit left child node (recursive)
- if rightChild[node] != -1: # check if there is right child
- isTree = isTree and self.visitNode(leftChild, rightChild, rightChild[node]) # now visit right child node (recursive)
- return isTree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement