[LeetCode]Unique Binary Search Trees II 唯一二叉树2

Unique Binary Search Trees II 唯一二叉树2

思路:利用回溯的思想,以其中一个值作为根结点,两边分别作为左结点和右结点的值。

class Solution(object):
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        def helper(start, end):
            res = []
            if start > end:
                res.append(None)
                return res
            for i in range(start, end+1):
                left_child = helper(start, i-1)
                right_child = helper(i+1, end)
                for left in left_child:
                    for right in right_child:
                        root = TreeNode(i)
                        root.left, root.right = left, right
                        res.append(root)
            return res
        if n < 1:
            return []
        return helper(1, n)
posted @ 2017-09-16 13:43  banananana  阅读(128)  评论(0编辑  收藏  举报