Unique Binary Search Trees II

Question

  1. Given n, generate all structurally unique BST's
  2. (binary search trees) that store values 1...n.
  3. Example
  4. Given n = 3, your program should return all 5 unique BST's shown below.
  5. 1 3 3 2 1
  6. \ / / / \ \
  7. 3 2 1 1 3 2
  8. / / \ \
  9. 2 1 2 3

题解

Unique Binary Search Trees 的升级版,这道题要求的不是二叉搜索树的数目,而是要构建这样的树。分析方法仍然是可以借鉴的,核心思想为利用『二叉搜索树』的定义,如果以 i 为根节点,那么其左子树由[1, i - 1]构成,右子树由[i + 1, n] 构成。要构建包含1到n的二叉搜索树,只需遍历1到n中的数作为根节点,以i为界将数列分为左右两部分,小于i的数作为左子树,大于i的数作为右子树,使用两重循环将左右子树所有可能的组合链接到以i为根节点的节点上。

容易看出,以上求解的思路非常适合用递归来处理,接下来便是设计递归的终止步、输入参数和返回结果了。由以上分析可以看出递归严重依赖数的区间和i,那要不要将i也作为输入参数的一部分呢?首先可以肯定的是必须使用『数的区间』这两个输入参数,又因为i是随着『数的区间』这两个参数的,故不应该将其加入到输入参数中。分析方便,不妨设『数的区间』两个输入参数分别为startend.

接下来谈谈终止步的确定,由于根据i拆分左右子树的过程中,递归调用的方法中入口参数会缩小,且存在start <= i <= end, 故终止步为start > end. 那要不要对start == end返回呢?保险起见可以先写上,后面根据情况再做删改。总结以上思路,简单的伪代码如下:

  1. helper(start, end) {
  2. result;
  3. if (start > end) {
  4. result.push_back(NULL);
  5. return;
  6. } else if (start == end) {
  7. result.push_back(TreeNode(i));
  8. return;
  9. }
  10. // dfs
  11. for (int i = start; i <= end; ++i) {
  12. leftTree = helper(start, i - 1);
  13. rightTree = helper(i + 1, end);
  14. // link left and right sub tree to the root i
  15. for (j in leftTree ){
  16. for (k in rightTree) {
  17. root = TreeNode(i);
  18. root->left = leftTree[j];
  19. root->right = rightTree[k];
  20. result.push_back(root);
  21. }
  22. }
  23. }
  24. return result;
  25. }

大致的框架如上所示,我们来个简单的数据验证下,以[1, 2, 3]为例,调用堆栈图如下所示:

  1. helper(1,3)
    • [leftTree]: helper(1, 0) ==> return NULL
    • —-loop i = 2—-
    • [rightTree]: helper(2, 3)
      1. [leftTree]: helper(2,1) ==> return NULL
      2. [rightTree]: helper(3,3) ==> return node(3)
      3. [for loop]: ==> return (2->3)
    • —-loop i = 3—-
      1. [leftTree]: helper(2,2) ==> return node(2)
      2. [rightTree]: helper(4,3) ==> return NULL
      3. [for loop]: ==> return (3->2)

简单验证后可以发现这种方法的核心为递归地构造左右子树并将其链接到相应的根节点中。对于startend相等的情况的,其实不必单独考虑,因为start == end时其左右子树均返回空,故在for循环中返回根节点。当然单独考虑可减少递归栈的层数,但实际测下来后发现运行时间反而变长了不少 :(

Python

  1. """
  2. Definition of TreeNode:
  3. class TreeNode:
  4. def __init__(self, val):
  5. this.val = val
  6. this.left, this.right = None, None
  7. """
  8. class Solution:
  9. # @paramn n: An integer
  10. # @return: A list of root
  11. def generateTrees(self, n):
  12. return self.helper(1, n)
  13. def helper(self, start, end):
  14. result = []
  15. if start > end:
  16. result.append(None)
  17. return result
  18. for i in xrange(start, end + 1):
  19. # generate left and right sub tree
  20. leftTree = self.helper(start, i - 1)
  21. rightTree = self.helper(i + 1, end)
  22. # link left and right sub tree to root(i)
  23. for j in xrange(len(leftTree)):
  24. for k in xrange(len(rightTree)):
  25. root = TreeNode(i)
  26. root.left = leftTree[j]
  27. root.right = rightTree[k]
  28. result.append(root)
  29. return result

C++

  1. /**
  2. * Definition of TreeNode:
  3. * class TreeNode {
  4. * public:
  5. * int val;
  6. * TreeNode *left, *right;
  7. * TreeNode(int val) {
  8. * this->val = val;
  9. * this->left = this->right = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @paramn n: An integer
  17. * @return: A list of root
  18. */
  19. vector<TreeNode *> generateTrees(int n) {
  20. return helper(1, n);
  21. }
  22. private:
  23. vector<TreeNode *> helper(int start, int end) {
  24. vector<TreeNode *> result;
  25. if (start > end) {
  26. result.push_back(NULL);
  27. return result;
  28. }
  29. for (int i = start; i <= end; ++i) {
  30. // generate left and right sub tree
  31. vector<TreeNode *> leftTree = helper(start, i - 1);
  32. vector<TreeNode *> rightTree = helper(i + 1, end);
  33. // link left and right sub tree to root(i)
  34. for (int j = 0; j < leftTree.size(); ++j) {
  35. for (int k = 0; k < rightTree.size(); ++k) {
  36. TreeNode *root = new TreeNode(i);
  37. root->left = leftTree[j];
  38. root->right = rightTree[k];
  39. result.push_back(root);
  40. }
  41. }
  42. }
  43. return result;
  44. }
  45. };

Java

  1. /**
  2. * Definition of TreeNode:
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left, right;
  6. * public TreeNode(int val) {
  7. * this.val = val;
  8. * this.left = this.right = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @paramn n: An integer
  15. * @return: A list of root
  16. */
  17. public List<TreeNode> generateTrees(int n) {
  18. return helper(1, n);
  19. }
  20. private List<TreeNode> helper(int start, int end) {
  21. List<TreeNode> result = new ArrayList<TreeNode>();
  22. if (start > end) {
  23. result.add(null);
  24. return result;
  25. }
  26. for (int i = start; i <= end; i++) {
  27. // generate left and right sub tree
  28. List<TreeNode> leftTree = helper(start, i - 1);
  29. List<TreeNode> rightTree = helper(i + 1, end);
  30. // link left and right sub tree to root(i)
  31. for (TreeNode lnode: leftTree) {
  32. for (TreeNode rnode: rightTree) {
  33. TreeNode root = new TreeNode(i);
  34. root.left = lnode;
  35. root.right = rnode;
  36. result.add(root);
  37. }
  38. }
  39. }
  40. return result;
  41. }
  42. }

源码分析

  1. 异常处理,返回None/NULL/null.
  2. 遍历start->end, 递归得到左子树和右子树。
  3. 两重for循环将左右子树的所有可能组合添加至最终返回结果。

注意 DFS 辅助方法helper中左右子树及返回根节点的顺序。

复杂度分析

递归调用,一个合理的数组区间将生成新的左右子树,时间复杂度为指数级别,使用的临时空间最后都被加入到最终结果,空间复杂度(堆)近似为 O(1), 栈上的空间较大。

Reference