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

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

dfs

重点是generateTrees_recur里面的 s>t条件判断之后的返回值是啥; 另外一个重点是边界条件判断,if n ==0

  # 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 generateTrees(self, n):
          """
          :type n: int
          :rtype: List[TreeNode]
          """
          if n==0: return []
          return self.generateTrees_recur(1, n)

      def generateTrees_recur(self, s, t):
          if s > t: return [None]
          result = []
          for k in range(s, t+1):
              v1 = self.generateTrees_recur(s,k-1)
              v2 = self.generateTrees_recur(k+1, t)
              for t1 in v1:
                  for t2 in v2:
                      r = TreeNode(k)
                      r.left = t1
                      r.right = t2
                      result.append(r)
          return result