LintCode-不同的二叉查找树 II
来源:互联网 发布:手机数据线线芯排序 编辑:程序博客网 时间:2024/05/16 15:30
给出n,生成所有由1...n为节点组成的不同的二叉查找树
样例
给出n = 3,生成所有5种不同形态的二叉查找树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
分析:以每个数字为head,然后递归产生就行。
代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @paramn n: An integer * @return: A list of root */ vector<TreeNode *> generateTrees(int n) { // write your code here vector<TreeNode *> ret = generateTrees(1,n); return ret; } vector<TreeNode*> generateTrees(int start,int end) { vector<TreeNode*> ret; if(start>end) { ret.push_back(nullptr); return ret; } if(start==end) { ret.push_back(new TreeNode(start)); return ret; } for(int i=start;i<=end;i++) { vector<TreeNode*> left = generateTrees(start,i-1); vector<TreeNode*> right = generateTrees(i+1,end); for(auto l:left) { for(auto r:right) { TreeNode* head = new TreeNode(i); head->left = l; head->right = r; ret.push_back(head); } } } return ret; }};
0 1
- LintCode-不同的二叉查找树 II
- 不同的二叉查找树 II lintcode
- 不同的二叉查找树 II -LintCode
- lintcode--不同的二叉查找树II
- **[Lintcode]Unique Binary Search Trees II 不同的二叉查找树 II
- LintCode-不同的二叉查找树
- lintcode-不同的二叉查找树-163
- LintCode 不同的二叉查找树
- LintCode:不同的二叉查找树
- lintcode,不同的二叉查找树
- LintCode 163-不同的二叉查找树
- LintCode :不同的二叉查找树
- lintcode-不同的二叉查找树
- 不同的二叉查找树-LintCode
- lintcode --不同的二叉查找树
- lintcode:不同的二叉查找树
- 题目:不同的二叉查找树 II
- 不同的二叉查找树 II
- 解决网络传输的过程中,出现乱码的问题
- 多线程创建方法总结
- mac上修改文件的显示与隐藏 隐藏文件 文件属性
- bnu 45519
- 如何做一个简单的开放接口(1)-功能设计
- LintCode-不同的二叉查找树 II
- extract initrd on ubuntu
- 图像腐蚀
- 直接插入排序
- TCP拥塞控制机制
- [leetcode][Search] Search a 2D Matrix
- 线段树辅助——扫描线法计算矩形面积并
- MATLAB 对图像的几何处理 system generator
- 扫描线矩形面积交