LeetCode 95 Unique Binary Search Trees II

标签: 二叉搜索树 LeetCode 发布于:2022-02-07 14:27:05 编辑于:2022-02-07 14:41:33 浏览量:901

概述

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

递归法

class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        return helper(1, n);
    }
    
    vector<TreeNode*> helper(int l, int r) {
        vector<TreeNode*> ans;
        if (l > r) {
            ans.push_back(nullptr);  // make sure there is at least one emelent
            return ans;
        }
        for (int i = l; i <= r; i ++) {
            auto lnodes = helper(l, i - 1);
            auto rnodes = helper(i + 1, r);
            for (auto lnode : lnodes) {
                for (auto rnode : rnodes) {
                    ans.push_back(new TreeNode(i, lnode, rnode));
                }
            }
        }
        return ans;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/