Unique Binary Search Trees II
2015-11-11 15:20
441 查看
题目:
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
题目:
这题要求将每个子树输出,思想就是对于n,以1-n为根节点,然后左右子树分别是比其小和比其大的节点构成的,对左右子树的的形态也要使用遍历,代码中使用的是foreach遍历:for(i:j)这种形式
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.
题目:
这题要求将每个子树输出,思想就是对于n,以1-n为根节点,然后左右子树分别是比其小和比其大的节点构成的,对左右子树的的形态也要使用遍历,代码中使用的是foreach遍历:for(i:j)这种形式
/** * 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); return generate(1, n); } private: vector<TreeNode *> generate(int start, int end) { vector<TreeNode*> subTree; if (start > end) { subTree.push_back(nullptr); return subTree; } for (int k = start; k <= end; k++) { vector<TreeNode*> leftSubs = generate(start, k - 1); vector<TreeNode*> rightSubs = generate(k + 1, end); for (auto i : leftSubs) { for (auto j : rightSubs) { TreeNode *node = new TreeNode(k); node->left = i; node->right = j; subTree.push_back(node); } } } return subTree; } };
相关文章推荐
- 下载的pod链接失效,build diff: /../Podfile.lock: No such file or directory解决办法
- leetcode range sum query
- [leetcode] Range Sum Query - Immutable
- ios uilocalnotification 多个本地通知,怎么有区分的删除
- 一个滑出view 的动画
- [LeetCode]Range Sum Query - Immutable
- UITextView 限制字符长度
- 苹果开发 笔记(92) UINavigationBar UITabBar
- UIWindow简单介绍
- SVN报MKCOL request for ... 405 Method Not Allowed错误
- about ANSI escape sequences
- HDU 5538 L - House Building 水题
- 权限添加 easyui datagrid toolbar 隐藏
- Android开发UI之ActionBar的覆盖叠加
- description The server refused this request because the request entity is in a format not supported
- UIView(window,frame,UIColor,CGPoint,alpha,CGRect等)
- UIView全部API
- Android开发UI之自定义ActionBar的风格
- Unique Binary Search Trees
- Exported service does not require permission