Simple Python DFS (pre-order) recursive solution - O(n) - 40ms


  • 0
    S
    class Solution:
        # @param {TreeNode} p
        # @param {TreeNode} q
        # @return {boolean}
        def isSameTree(self, p, q):
            # Both None
            if not p and not q: return True
            # Both active
            if p and q: 
                if p.val != q.val: return False
            else:
                return False
    
            return 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.