Iven 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.
Basic idea: Recursion
1. Each element in turn is the root node
2. Recursively, all elements to the left of the element, returning a collection of sets of numbers.
3. All elements to the right of the element, generating a set of numbers.
4. Select a tree from the left and right sets to Saozi the right subtree, together with the root node. Make up a tree.
On Leetcode, the actual execution time is 27ms.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {Public:vector<treenode *> generatetrees (int n) {vector<treenode *> ans; Generatetrees (ans, 1, n+1); return ans; } void Generatetrees (Vector<treenode *> &ans, int start, int stop) {for (int i=start; i<stop; i++) {Vector<treenode *> lefts; Generatetrees (lefts, start, i); for (int j=0; j<lefts.size (); j + +) {Vector<treenode *> rights; Generatetrees (Rights, i+1, stop); for (int k=0; k<rights.size (); k++) {TreeNode *root = new TreeNode (i); Root->left = Lefts[j]; Root->right = Rights[k]; Ans.push_back (root); } } } if (Ans.empty ()) ans.push_back (0); }};
Unique Binary Search Trees II--Leetcode