Leaf Similar Trees (Leetcode 872)

Technique: FAITH technique of Recursion

Problem Link: https://leetcode.com/problems/leaf-similar-trees/

class Solution:

    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        
        global ans
        ans=[]
        
        def fun(root):
            if(root is None):
                return
            if(root.left is None and root.right is None):
                ans.append(root.val)
                return
            fun(root.left)
            fun(root.right)
            
        fun(root1)
        fun(root2)
        if(len(ans)%2!=0):
            return False
        m=len(ans)//2
        for i in range(m):
            if(ans[i]!=ans[i+m]):
                return False
        else:
            return True

Last updated