19.2.24 [LeetCode 95] Unique Binary Search Trees II

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:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

题意

给定一数n,求1-n所组成的所有可能的BST树的集合

题解

 1 class Solution {
 2 public:
 3     vector<TreeNode*> build(int s, int e) {
 4         if (s > e)return vector<TreeNode*>();
 5         vector<TreeNode*>ans;
 6         if (s == e) {
 7             TreeNode*tmp = new TreeNode(s);
 8             ans.push_back(tmp);
 9             return ans;
10         }
11         for (int i = s; i <= e; i++) {
12             vector<TreeNode*>left = build(s, i - 1), right = build(i + 1, e);
13             for(int j=0;j<left.size();j++)
14                 for (int k = 0; k < right.size(); k++) {
15                     TreeNode*tmp = new TreeNode(i);
16                     tmp->left = left[j], tmp->right = right[k];
17                     ans.push_back(tmp);
18                 }
19             if (left.size() == 0 || right.size() == 0) {
20                 for (int j = 0; j < left.size(); j++) {
21                     TreeNode*tmp = new TreeNode(i);
22                     tmp->left = left[j];
23                     ans.push_back(tmp);
24                 }
25                 for (int j = 0; j < right.size(); j++) {
26                     TreeNode*tmp = new TreeNode(i);
27                     tmp->right = right[j];
28                     ans.push_back(tmp);
29                 }
30             }
31         }
32         return ans;
33     }
34     vector<TreeNode*> generateTrees(int n) {
35         return build(1, n);
36     }
37 };
View Code

 

posted @ 2019-02-24 22:08  TobicYAL  阅读(195)  评论(0编辑  收藏  举报