Unique Binary Search Trees Series
Question
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
Given n = 3, there are a total of 5 unique BST’s.
|
|
Analysis
对于数字范围1-n,可能任意选择其中的x作为树的根,以x为根的树的种类数是[1,x-1]和[x+1,n]可形成的左右子树个数的乘积和。
Code
|
|
Unique Binary Search Trees Series II
Question
Given an integer 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.
|
|
Analysis
原理同上,只不过得到的不是树的个数而是左右子树的节点,然后利用循环进行组合
Code
|
|