Title Description:
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
Thinking Analysis: Let 1-n do root respectively. When Root is I, Zuozi is composed of 1~i-1 and the right subtree is composed of i+1~n. The recursive method is used to solve the left and right sub-trees, and then all possible solutions of the subtree are combined together to obtain all possible BST.
Code:
Vector<treenode *> gettrees (int start,int end) { Vector<treenode *> result; if (Start > End) { result.push_back (NULL); return result; } if (start = = end) { TreeNode * new_node = new TreeNode (start); Result.push_back (New_node); return result; } for (int i = start;i <= end, i++) { Vector<treenode *> left = gettrees (start,i-1); Vector<treenode *> right = Gettrees (i+1,end); For (TreeNode * left_node:left) for (TreeNode * right_node:right) { TreeNode * new_node = new TreeNode (i); new_node->left = Left_node; New_node->right = Right_node; Result.push_back (New_node); } } return result;} Vector<treenode *> solution::generatetrees (int n) { return gettrees (1,n);}
Leetcode:unique Binary Search Trees II