96 & 95. Unique Binary Search Tree I & II

96. Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

My Solutions:

对于数组【1,2,3,4,5,6】来说,如果让4做root,结果就是[1,2,3]可以组成的树的数量乘以[5,6]可以组成树的数量。

如果数组为空,毫无疑问,只有一种BST,即空树,
Count[0] =1

如果数组仅有一个元素{1},只有一种BST,单个节点
Count[1] = 1

如果数组有两个元素{1,2}, 那么有如下两种可能
1                       2
  \                    /
    2                1
Count[2] = Count[0] * Count[1]   (1为根的情况,左子树一定不存在,右子树可以有一个数字)
         + Count[1] * Count[0]  (2为根的情况,左子树可以有一个数字,右子树一定不存在)

再看一个三个元素的数组,可以发现BST的取值方式如下:
Count[3] = Count[0]*Count[2]  (1为根的情况,左子树一定不存在,右子树可以有两个数字)
         + Count[1]*Count[1]  (2为根的情况,左右子树都可以各有一个数字)
         + Count[2]*Count[0]  (3为根的情况,左子树可以有两个数字,右子树一定不存在)

95. Unique Binary Search Trees II

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

Example 1:

Example 2:

和#96类似,要求返回所有的树。

My Solutions:

Last updated