Python O(n) solution using two lists


  • 0
    C

    I thought this approach was neat.

    class Solution(object):
        def isSameTree(self, p, q):
       
            pList = self.preorder(p)
            qList = self.preorder(q)
            
            if len(pList) != len(qList):
                return False
            
            for i in range( len(pList) ):
                if pList[i] != qList[i]:
                    return False
            
            return True
            
            
        def preorder (self, node):
            res = []
            self.doPreorder(node, res)
            return res
        
        def doPreorder(self, node, result):
            if not node:
                result.append(None)
                return
            result.append(node.val)
            self.doPreorder(node.left, result)
            self.doPreorder(node.right, result)
            
    

Log in to reply
 

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