Search code examples
binary-tree

Why Am I not getting expected output?


I am a beginner in trees.I defined a findNode function to return the node.Then I recursively check if both node as root and subtree is same.But I have not getting the expected output for the below test case. How can it be altered. Thanks in advance

Expected output:true

Input: Tree:[1,1]

subTree:[1]

but the output I am getting is false

leetcode problem: https://leetcode.com/problems/subtree-of-another-tree/submissions/

    def findNode(self,root,subRoot):
        if root==None:
            return None
        if root.val==subRoot.val:
            return root
        if root.left:
            return self.findNode(root.left,subRoot)
        if root.right:
            return self.findNode(root.right,subRoot)
        
    def check(self,root,subRoot):
        if root==None and subRoot==None:
            return True
        if root==None or subRoot==None:
            return False
        if root.val!=subRoot.val:
            return False
        return self.check(root.right,subRoot.right) and self.check(root.left,subRoot.left)
    
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        node=self.findNode(root,subRoot)
        return self.check(node,subRoot)
    ```

Solution

  • There was a problem in your code because once you find a matching node with subRoot node you stop searching and you run check() function, which can return false and your program will return that false without checking deeper subtrees, which can be matched. Here is my code:

    class Solution:
        def findMatchingTree(self,root,subRoot):
            if root==None:
                return False
            return self.check(root, subRoot) or self.findMatchingTree(root.left,subRoot) or self.findMatchingTree(root.right,subRoot)
            
        def check(self,root,subRoot):
            if root==None and subRoot==None:
                return True
            if root==None or subRoot==None:
                return False
            if root.val!=subRoot.val:
                return False
            return self.check(root.right,subRoot.right) and self.check(root.left,subRoot.left)
        
        def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
            return self.findMatchingTree(root,subRoot)
    

    If you want to make code faster I suggests you to search for roots from the leafs of tree.