【LEETCODE】95-Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,

Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1

    \       /     /      / \      \

     3     2     1      1   3      2

    /     /       \                 \

   2     1         2                 3


参考:

http://www.cnblogs.com/zuoyuan/p/3752428.html

http://algorithm.yuanbin.me/zh-cn/exhaustive_search/unique_binary_search_trees_ii.html

http://chaoren.is-programmer.com/posts/42908.html


『二叉搜索树』的定义,如果以 i 为根节点,那么其左子树由[1, i - 1]构成,右子树由[i + 1, n] 构成。


“必须使用『数的区间』这两个输入参数

不妨设『数的区间』两个输入参数分别为start和end

接下来谈谈终止步的确定,由于根据i拆分左右子树的过程中

start <= i <= end, 故终止步为start > end”


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    
    def dfs(self,start,end):
        
        ans=[]
        
        if start>end:                                #把最底层的root控制到了start==end时
            ans.append(None)
            return ans
        
        for r in range(start,end+1):                 #root从start到end
            
            lefttree=self.dfs(start,r-1)             #比root小的都放在左支树
            righttree=self.dfs(r+1,end)              #比root大的都放在右支树
            
            for i in lefttree:
                for j in righttree:
                    root=TreeNode(r)                 #直到最后一个点成为子树的root时
                    root.left=i
                    root.right=j
                    ans.append(root)
                    
        return ans
        
        
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        return self.dfs(1,n)



你可能感兴趣的:(LeetCode,python)