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.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
This question is the first unique binary search Trees the only two-fork tree extension, before that only asked to calculate the number of all the different two-fork search tree, the problem so that the binary trees are established. In general, this kind of achievement problem is the recursive solution, the question is no exception, dividing the left and right sub-tree, recursive structure. As for why the recursive function is used in the pointer, is a reference to the user in the water of the fish blog, if not the pointer, all instances will have a large number of object copies, to call the copy constructor, specifically I do not understand, anyway, it feels quite reasonable, unknown feeling Li Ah-.-!!!
/** 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) {return*generatetreesdfs (1, N); } Vector<TreeNode*> *generatetreesdfs (intStartintend) {Vector<TreeNode*> *subtree =NewVector<treenode*>(); if(Start > End) subtree->push_back (NULL); Else { for(inti = start; I <= end; ++i) {vector<TreeNode*> *leftsubtree = Generatetreesdfs (Start, I-1); Vector<TreeNode*> *rightsubtree = Generatetreesdfs (i +1, end); for(intj =0; J < Leftsubtree->size (); ++j) { for(intK =0; K < Rightsubtree->size (); ++k) {TreeNode*node =NewTreeNode (i); Node->left = (*Leftsubtree) [j]; Node->right = (*Rightsubtree) [K]; Subtree-push_back (node); } } } } returnsubtree; }};
[Leetcode] Unique binary Search Trees II is the only two of the two-fork searching tree