Участник:Никита Плетнев/unique binary search trees ii

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/unique-binary-search-trees-ii/submissions/

/**
 * 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*> allTreesFromRange(int begin_, int end_) {
        vector<TreeNode*> result;
        if (begin_ >= end_) {
            result.push_back(NULL);
            return result;
        }
        for (int m = begin_; m < end_; ++m) {
            vector<TreeNode*> left_subtrees = allTreesFromRange(begin_, m);
            vector<TreeNode*> right_subtrees = allTreesFromRange(m + 1, end_);
            for (auto it = left_subtrees.begin(); it < left_subtrees.end(); ++it) {
                for (auto jt = right_subtrees.begin(); jt < right_subtrees.end(); ++jt) {
                    TreeNode* root = new TreeNode(m, *it, *jt);
                    result.push_back(root);
                }
            }
        }
        return result;
    }
 
    vector<TreeNode*> generateTrees(int n) {
        if (n == 0)
            return {};
        return allTreesFromRange(1, n + 1);
    }
};