iterative Python beats 99.5%


  • 0
    C

    everyone posts recursive method, here I add an iterative way using stack.

        def isSameTree(self, p, q):
    
            if not p and not q: return True
            if not p or not q: return False
            
            stackp = [p]
            stackq = [q]
            
            while stackp and stackq:
                nodep = stackp.pop()
                nodeq = stackq.pop()
                
                if nodep.val != nodeq.val:
                    return False
                if nodep.left and nodeq.left:
                    stackp.append(nodep.left)
                    stackq.append(nodeq.left)
                elif not nodep.left and not nodeq.left:
                    pass
                else:
                    return False
                if nodep.right and nodeq.right:
                    stackp.append(nodep.right)
                    stackq.append(nodeq.right)
                elif not nodep.right and not nodeq.right:
                    pass
                else:
                    return False
                
            return True
    

Log in to reply
 

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