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.
基本思路:递归
1. 依次以每个元素为根节点
2. 进行递归,该元素左边的所有元素,返回一组数的集合。
3. 该元素右边的所有元素,生成一组数的集合。
4. 分别从左边、右边集合各挑选一棵树作为左子树和右子树,连同根结点。组成一个棵树。
在leetcode上,实际执行时间为27ms。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(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
原文地址:http://blog.csdn.net/elton_xiao/article/details/45440531