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
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: AVector<treenode*> Generatetrees (intN) { -Vector<treenode*>ans; -Ans=generate (1, n); the returnans; - } -Vector<treenode*> Generate (intAintb) - { +Vector<treenode*>ans; - if(a>b) + returnans; A if(a==b) at { -TreeNode *temp=NewTreeNode (a); - Ans.push_back (temp); - returnans; - } -Vector<treenode*> Vt1=generate (A +1, b); in for(intI=0; I<vt1.size (); i++) - { toTreeNode *tr1=NewTreeNode (a);//cannot be placed outside, otherwise, the TR1 in ans will become all the same. (TR1 same, tr1->right is different, therefore should be multi-points TR1) +tr1->right=Vt1[i]; - ans.push_back (TR1); the } * $Vector<treenode*> Vt2=generate (a,b-1);Panax Notoginseng for(intI=0; I<vt2.size (); i++) - { theTreeNode *tr2=NewTreeNode (b); +tr2->left=Vt2[i]; A Ans.push_back (TR2); the } + - for(inti=a+1; i<=b-1; i++) $ { $Vector<treenode*> Vt31=generate (a,i-1); -Vector<treenode*> Vt32=generate (i+1, b); - for(intj=0; J<vt31.size (); j + +) the { - for(intk=0; K<vt32.size (); k++)Wuyi { theTreeNode *tr3=NewTreeNode (i); -tr3->left=Vt31[j]; Wutr3->right=Vt32[k]; - Ans.push_back (TR3); About } $ } - - - } A returnans; + } the};
View Code
Leetcode95 Unique Binary Search Trees II