Cousins in a Binary Tree (Leetcode 993)

Problem Link: https://leetcode.com/problems/cousins-in-binary-tree/

class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        
        
        self.xheight=0
        self.yheight=0
        self.res=0
        def fun(root,x,y,depth):
            if(root is None):
                return
            if(root.left is not None and root.right is not None):
                if(root.left.val==x and root.right.val==y):
                    self.res=1
                if(root.left.val==y and root.right.val==x):
                    self.res=1
            if(root.val==x):
                self.xheight=depth
            elif(root.val==y):
                self.yheight=depth
            
            fun(root.left,x,y,depth+1)
            fun(root.right,x,y,depth+1)
            
            
        fun(root,x,y,0)
        if(self.xheight!=self.yheight or self.res==1):
            return False
        else:
            return True

Last updated