Unique Binary Search Trees II

    xiaoxiao2025-01-25  9

    Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.

    For example, Given n = 3, your program should return all 5 unique BST's shown below.

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

    Subscribe to see which companies asked this question

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> help(int start,int end) { vector<TreeNode*> ans; if(start>end) { ans.push_back(NULL); } for(int i=start;i<=end;++i) { vector<TreeNode*> left = help(start,i-1); vector<TreeNode*> right=help(i+1,end); for(auto l:left) for(auto r:right) { TreeNode* root = new TreeNode(i); root->left = l; root->right = r; ans.push_back(root); } } return ans; } vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> ans; if(n<0) return ans; for(int i=1;i<=n;++i) { vector<TreeNode*> left = help(1,i-1); vector<TreeNode*> right=help(i+1,n); for(auto l:left) for(auto r:right) { TreeNode* root = new TreeNode(i); root->left = l; root->right = r; ans.push_back(root); } } return ans; } };
    转载请注明原文地址: https://ju.6miu.com/read-1295775.html
    最新回复(0)