"title"
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
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"Analysis"
Reference: [Leetcode]96.unique Binary Search Trees
"Code"
/********************************** Date: 2014-12-27* sjf0115* title: 95.Unique Binary Search Trees ii* Source: Https://oj.le etcode.com/problems/unique-binary-search-trees-ii/* results: ac* Source: leetcode* Summary: **********************************/# Include <iostream> #include <vector>using namespace std;struct TreeNode {int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (NULL) {}};class solution {Public:vector<treenode *> generatetrees (in T n) {if (n <= 0) {return generate (1, 0); }//if else{return Generate (1, n); }}//private://Return root node combined with vector<treenode*> generate (int start,int end) {vector<treenode*> subt Ree if (Start > End) {subtree.push_back (NULL); return subtree; }//if//I as the root node for (int i = Start;i <= end;i++) {//with I as the root node of the tree, the left subtree is composed of [start,i-1], the right subtree by [I+1,end] Constitute. Returned is notThe root node of the same binary lookup tree, several two-fork lookup trees return several root nodes vector<treenode*> Leftsubtree = Generate (Start,i-1); Vector<treenode*> rightsubtree = Generate (I+1,end); Zuozi the right subtree is connected to the root node//the number of trees rooted in I, equal to the number of left subtrees multiplied by the number of right subtrees for (int j = 0;j < Leftsubtree.size (); j + +) { for (int k = 0;k < Rightsubtree.size (); k++) {treenode* node = new TreeNode (i); Node->left = Leftsubtree[j]; Node->right = Rightsubtree[k]; Subtree.push_back (node); }//for}//for}//for return subtree; }//};//first-order traversal of void preorder (treenode* root) {if (root = NULL) {return; }//if cout<<root->val<< ""; Preorder (Root->left); Preorder (root->right);} int main () {solution solution; vector<treenode*> VEC = solution.generatetrees (3); for (int i = 0;i < Vec.size (); i++) {treenode* root = Vec[i]; PreordER (root); cout<<endl; }}
[Leetcode]95.unique Binary Search Trees II