Python iterative + recursive solution


  • 0
    H

    Iterative solution:

    class Solution(object):
        def isSameTree(self, p, q):
            """
            :type p: TreeNode
            :type q: TreeNode
            :rtype: bool
            """
            stack = [(p, q)]
            while stack:
                n, m = stack.pop()
                if n and m:
                    if n.val != m.val:
                        return False
                    stack.append((n.right, m.right))
                    stack.append((n.left, m.left))
                elif n is not m:
                    return False
            return True
    

    Recursive solution:

    class Solution(object):
        def isSameTree(self, p, q):
            """
            :type p: TreeNode
            :type q: TreeNode
            :rtype: bool
            """
            if p is None and q is None:
                return True
            elif p is None or q is None:
                return False   
            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.