Unique Binary Search Trees II
Given 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
Since 1~n is the ascending sequence, the tree that is built naturally is BST.
Recursive thinking, select the root node, and then separate the left and right sub-sequences.
Since the results of the left and right sub-sequences may be more than one, consideration should be given to all collocation situations.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<treenode *> Generatetrees (intN) {vector<treenode *>Res; if(n = =0) {res.push_back (NULL); returnRes; } Else { returnHelper (1, N); }} vector<TreeNode*> Helper (intBeginintend) {Vector<TreeNode*>Res; if(Begin >end) {Res.push_back (NULL); returnRes; } Else if(Begin = =end) {TreeNode* Root =NewTreeNode (begin); Res.push_back (root); returnRes; } Else { for(inti = begin; I <= end; i + +) { //TagVector<treenode*> left = Helper (begin, I-1); Vector<TreeNode*> right = Helper (i+1, end); for(intL =0; L < Left.size (); L + +) {//All BST in left for(intR =0; R < Right.size (); R + +) {//All BST on right//New root here! not the tag position.treenode* root =NewTreeNode (i); Root->left =Left[l]; Root->right =Right[r]; Res.push_back (root); } } } returnRes; } }};
"Leetcode" Unique Binary Search Trees II