LeetcodeUnique Binary Search Trees II
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeUnique Binary Search Trees II相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/unique-binary-search-trees-ii/
题目:
Given 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.
1 3 3 2 1 \\ / / / \\ \\ 3 2 1 1 3 2 / / \\ \\ 2 1 2 3
思路:
当根结点分别为1~n时,递归遍历,根结点大于左子树小于右子树。
算法:
public List<TreeNode> generateTrees(int n) {
if (n == 0)
return null;
return dsp(1, n);
}
public List<TreeNode> dsp(int start, int end) {
List<TreeNode> res = new ArrayList<TreeNode>();
if (start > end) {
res.add(null);
return res;
}
for (int i = start; i <= end; i++) {
List<TreeNode> left = dsp(start, i - 1);
List<TreeNode> right = dsp(i + 1, end);
for (TreeNode l : left) {
for (TreeNode r : right) {
TreeNode root = new TreeNode(i);
root.left = l;
root.right = r;
res.add(root);
}
}
}
return res;
}
以上是关于LeetcodeUnique Binary Search Trees II的主要内容,如果未能解决你的问题,请参考以下文章
convert-sorted-list-to-binary-search-tree
convert-sorted-list-to-binary-search-tree