95. Unique Binary Search Trees II
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
Topic: Given the value n, return all possible BSTs consisting of 1. n. Note that a BST only needs to return a root pointer.
Ideas: See also https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31494/A-simple-recursive-solution . For BST with root node i, the left subtree left contains elements of start..i-1 and right subtree right contains elements of I + 1.. End. Assuming that lefts is a set of all possible left subtrees (each subtree has only a head node), right is a set of all right subtrees, then for BST with root i, only lefts and HTS need to be combined. The root nodes at different locations in the range of [start,end] are recursively iterated.
Same thinking LeetCode241. Different Ways to Add Parentheses.
/** * 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*> generateTrees(int n) { if(n < 1) return vector<TreeNode*>{}; return generateTrees(1, n); } private: vector<TreeNode*> generateTrees(int start, int end){ vector<TreeNode*> res; if(start > end){ res.push_back(nullptr); return res; } if(start == end){ TreeNode* root = new TreeNode(start); res.push_back(root); return res; } //In the range of `[start, end]', for the case where root node is i for(int i = start; i <= end; ++i){ //Notice the left boundary of left and the right boundary of right. vector<TreeNode*> left = generateTrees(start, i-1); vector<TreeNode*> right = generateTrees(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; } };