题目描述
题目难度:Medium
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
Example:
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:
AC代码
涉及到树的算法一般都会用到递归,参考了leetcode上面的解法.
class Solution {
public List<TreeNode> generateTrees(int n) {
if (n == 0) return new ArrayList<>();
return generateTrees(1, n);
}
private List<TreeNode> generateTrees(int left, int right) {
final List<TreeNode> res = new ArrayList<>();
if (left > right) {
res.add(null);
return res;
} else if (left == right) {
res.add(new TreeNode(left));
return res;
}
for (int i = left; i <= right; i++) {
final List<TreeNode> leftSub = generateTrees(left, i - 1);
final List<TreeNode> rightSub = generateTrees(i + 1, right);
for (final TreeNode x : leftSub) {
for (final TreeNode y : rightSub) {
final TreeNode root = new TreeNode(i);
root.left = x;
root.right = y;
res.add(root);
}
}
}
return res;
}
}