DFS python easy code


  • 1
    class Solution:
    # @return a list of tree node
    def generateTrees(self, n):
        return self.dfs(1,n)
        
    def dfs(self,start,end):
        res = []
        if start > end:
            res.append(None)
            return res
    
        for i in xrange(start,end+1):
            leftl = self.dfs(start,i-1)
            rightl = self.dfs(i+1,end)
            for l in xrange(0,len(leftl)):
                for r in xrange(0,len(rightl)):
                    node = TreeNode(i)
                    node.left = leftl[l]
                    node.right = rightl[r]
                    res.append(node)
        return res

Log in to reply
 

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