Leetcode 95. Unique Binary Search Tree II
由于BST的性质,所以右子树或者左子树中Node的值是连续的: 左子树 = [1, i -1], root = i, 右子树 = [i + 1, n]。使用一个递归函数构造这个BST。其中返回值应该是所有的Unique BST的root node。
1 def generateTrees(self, n): 2 """ 3 :type n: int 4 :rtype: List[TreeNode] 5 """ 6 if n == 0: 7 return [] 8 return self.buildTree(1, n) 9 10 def buildTree(self, start, end): 11 result = [] 12 if start > end: 13 result.append(None) 14 return result 15 16 for i in range(start, end + 1): 17 leftChild = self.buildTree(start, i - 1) 18 rightChild = self.buildTree(i+1, end) 19 20 for l in leftChild: 21 for r in rightChild: 22 node = TreeNode(i) 23 node.left = l 24 node.right = r 25 result.append(node) 26 27 return result