Validate Binary Tree
https://leetcode.com/problems/validate-binary-tree-nodes/
Union Find Approach
#check two conditions:
# (1) UnionFind Disjoint Set Count 1
# (2) In-degree sum of all nodes equal to n-1
class UnionFind(object):
def __init__(self,n):
self.parents = list(range(n))
self.count = n
def find(self,x):
if x != self.parents[x]:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self,x,y):
xSet = self.find(x)
ySet = self.find(y)
self.parents[ySet] = xSet
if xSet == ySet:
return False
self.count-=1
return True
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
inDegree = n * [0]
uf = UnionFind(n)
for parent, nodes in enumerate(zip(leftChild,rightChild)):
l,r = nodes
if l != -1:
uf.union(parent,l)
inDegree[l]+=1
if r != -1:
uf.union(parent,r)
inDegree[r] +=1
return sum(inDegree) == n-1 and uf.count==1
Last updated
Was this helpful?