首页 > 其他 > 详细

95. Unique Binary Search Trees II

时间:2021-01-10 22:53:56      阅读:45      评论:0      收藏:0      [点我收藏+]

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

 

Constraints:

  • 0 <= n <= 8
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    //递归
    vector<TreeNode*> generate(int start,int end){
        vector<TreeNode*> res;
        if(start > end) {
            res.push_back(NULL);
            return res;
        }
        if(start == end){
            TreeNode* node = new TreeNode(start);
            res.push_back(node);
            return res;
        }
        for(int i=start;i<=end;i++){
            vector<TreeNode*> left = generate(start,i-1);
            vector<TreeNode*> right = generate(i+1,end);
            for(auto l:left){
                for(auto r:right){
                    TreeNode* root = new TreeNode(i);
                    root->left = l;
                    root->right= r;
                    res.push_back(root);
                }
            }
        }
        return res;
    }
    
    vector<TreeNode*> generateTrees(int n) {
        if(n == 0) return vector<TreeNode*>{};
        return generate(1,n);
    }
};

 

95. Unique Binary Search Trees II

原文:https://www.cnblogs.com/wsw-seu/p/14258800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!