【LeetCode】Unique Binary Search Trees II
2014-08-16 16:42
337 查看
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
The above binary tree is serialized as
思路:看程序就可以看到是将1到n遍历,然后选择其中的i,将位于其左边的和位于其右边的都遍历加入到vector中。
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
思路:看程序就可以看到是将1到n遍历,然后选择其中的i,将位于其左边的和位于其右边的都遍历加入到vector中。
/** * 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 *> generate(int beg, int end) { vector<TreeNode *> ret; if(beg>end){ ret.push_back(NULL); return ret; } for(int i=beg;i<=end;i++){ vector<TreeNode *> TreeLeft = generate(beg, i-1); vector<TreeNode *> TreeRight = generate(i+1, end); for(int j=0;j<TreeLeft.size();j++){ for(int k=0;k<TreeRight.size();k++){ TreeNode* tmp = new TreeNode(i); tmp->left = TreeLeft[j]; tmp->right = TreeRight[k]; ret.push_back(tmp); } } } return ret; } vector<TreeNode *> generateTrees(int n) { return generate(1, n); } };
相关文章推荐
- [leetcode] 95. Unique Binary Search Trees II 解题报告
- 2 Unique Binary Search Trees II_Leetcode
- leetcode 刷题之路 50 Unique Binary Search Trees II
- LeetCode Unique Binary Search Trees II
- [LeetCode]题解(python):095-Unique Binary Search Trees II
- (Leetcode)Unique Binary Search Trees I & II
- Leetcode: Unique Binary Search Trees II
- LeetCode(95) Unique Binary Search Trees II
- leetcode Unique Binary Search Trees II java
- [Leetcode] Unique Binary Search Trees II
- 【leetcode】Unique Binary Search Trees II
- ***LeetCode 95. Unique Binary Search Trees II
- Leetcode---Unique Binary Search Trees II
- LeetCode --- 95. Unique Binary Search Trees II
- leetcode-Unique Binary Search Trees II
- [leetcode 95] Unique Binary Search Trees II
- leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法
- 【Leetcode】【python】Unique Binary Search Trees II
- LeetCode||95. Unique Binary Search Trees II
- [leetcode]Unique Binary Search Trees II