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. 1 3 3 2 1
  2. \ / / / \ \
  3. 3 2 1 1 3 2
  4. / / \ \
  5. 2 1 2 3

分析

见前面一题。

代码

  1. // Unique Binary Search Trees II
  2. // 时间复杂度TODO,空间复杂度TODO
  3. class Solution {
  4. public:
  5. vector<TreeNode *> generateTrees(int n) {
  6. if (n == 0) return vector<TreeNode*>();
  7. return generate(1, n);
  8. }
  9. private:
  10. vector<TreeNode *> generate(int start, int end) {
  11. vector<TreeNode*> subTree;
  12. if (start > end) {
  13. subTree.push_back(nullptr);
  14. return subTree;
  15. }
  16. for (int k = start; k <= end; k++) {
  17. vector<TreeNode*> leftSubs = generate(start, k - 1);
  18. vector<TreeNode*> rightSubs = generate(k + 1, end);
  19. for (auto i : leftSubs) {
  20. for (auto j : rightSubs) {
  21. TreeNode *node = new TreeNode(k);
  22. node->left = i;
  23. node->right = j;
  24. subTree.push_back(node);
  25. }
  26. }
  27. }
  28. return subTree;
  29. }
  30. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/binary-tree/bst/unique-binary-search-trees-ii.html