[95]Unique Binary Search Trees II
2015-10-29 20:27
537 查看
【题目描述】
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.
confused what
read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
【思路】
用递归实现的,思路基本和Unique Binary Search Trees一样。
【代码】
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.
Subscribe to see which companies asked this question
【思路】
用递归实现的,思路基本和Unique Binary Search Trees一样。
【代码】
/** * Definition for a binary tree node. * 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) { if(n==0) return generate(1,0); else return generate(1,n); } vector<TreeNode*> generate(int start,int end){ vector<TreeNode*> subtree; if(start>end){ subtree.push_back(NULL); return subtree; } for(int i=start;i<=end;i++){ vector<TreeNode*> lefttree=generate(start,i-1); vector<TreeNode*> righttree=generate(i+1,end); for(int j=0;j<lefttree.size();j++){ for(int k=0;k<righttree.size();k++){ TreeNode* node=new TreeNode(i); node->left=lefttree[j]; node->right=righttree[k]; subtree.push_back(node); } } } return subtree; } };
相关文章推荐
- iOS项目中的version和build
- Android 如何在自定义界面上启用输入法 (How to enable inputmethod for the custom UI)
- 【Android测试】【第十二节】Uiautomator——API详解
- 1041. Be Unique
- WeUI—微信官方UI库
- 十六进制颜色转换为iOS可以用的UIColor
- MySQL Row size too large (> 8126) 以及ROW_FORMAT=COMPRESSED requires innodb_file_format > Antel 的解决办法
- LeetCode Unique Binary Search Trees (DP)
- UIDevice
- 翻译:Fast Exact Shortest-Path Distance Queries on LargeNetworks by Pruned Landmark Labeling
- Warning: Attempt to present <UIImagePickerController: 0x292b400> on xxx which is already presenti
- [转]Android UI 自动化测试
- android-消息传递机制Message、MessageQueue、Handler、Looper
- hdu 5504 GT and sequence
- 关于UIInterfaceOritation 和 UIDeviceOritation
- 关于mysql的错误 - no query specified
- Android - Get Bluetooth UUID for this device
- iOS UI设计: 在Autolayout的布局上用constraint实现动画
- iOS流布局UICollectionView系列七——三维中的球型布局
- Requests高级用法