【LeetCode】C++ :中等题 - 树 95. 不同的二叉搜索树 II

95. 不同的二叉搜索树 II

难度中等776

给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 

 

示例:

输入:3
输出:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:

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

 

提示:

  • 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*> generateTrees(int n) {
        if(!n){
            return {};
        }
        return generateTrees(1, n);
    }
    vector<TreeNode*> generateTrees(int start, int end){
        if(start > end){
            return {nullptr};
        }
        vector<TreeNode*> allTrees;
        for(int i = start; i <= end; i++){
            vector<TreeNode*> leftTrees = generateTrees(start, i-1);
            vector<TreeNode*> rightTrees = generateTrees(i+1, end);

            for(auto& left: leftTrees){
                for(auto& right: rightTrees){
                    TreeNode* curr = new TreeNode(i);
                    curr->left = left;
                    curr->right = right;
                    allTrees.emplace_back(curr);
                }
            }
        }
        return allTrees;
    }
};

 

上一篇:95后买车怪象横生,名悦集团指点迷津


下一篇:95%的软件公司面试都会问的面试题大盘点