1.题目描述
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
Example:
1 | Input: 3 |
2.Solutions
迭代版本
I start by noting that 1..n is the in-order traversal for any BST with nodes 1 to n. So if I pick i-th node as my root, the left subtree will contain elements 1 to (i-1), and the right subtree will contain elements (i+1) to n. I use recursive calls to get back all possible trees for left and right subtrees and combine them in all possible ways with the root.
1 | public List<TreeNode> generateTrees(int n) { |
动态规划版本
1 | public static List<TreeNode> generateTreesDP(int n) { |
result[i] stores the result until length i. For the result for length i+1, select the root node j from 0 to i, combine the result from left side and right side. Note for the right side we have to clone the nodes as the value will be offsetted by j.