题目:构建二叉树
Given an integer n
, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Constraints:
0 <= n <= 8
首先,熟悉一下构建二叉树:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int cnt = 0;
void buildTree(TreeNode* root,vector<char> data)
{
if(cnt < data.size() && data[cnt] == '#')
root = NULL;
else
{
root = new TreeNode(data[cnt++]);
buildTree(root->left,data);
buildTree(root->right,data);
}
}
};
算法解析:
Given a tree which n nodes, it has the follwing form:
(0)root(n-1)
(1)root(n-2)
(2)root(n-3)
where (x) denotes the trees with x nodes.
Now take n=3 for example. Given n=3, we have [1 2 3] in which each of them can be used as the tree root.
when root=1: [1 # 2 # 3]; [1 # 3 2];
when root=2: [2 1 3];
when root=3: (similar with the situations when root=1.)
Thus, if we write a recursive function who generates a group of trees in which the numbers range from f to t, we have to generate the left trees and right trees of each tree in the vector.
I give the following recursive code and expect to see non-recursive ones. please!
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> genTree(int start, int end)
{
vector<TreeNode*> res;
if(start > end)
{
res.push_back(NULL);
return res;
}
else if(start == end)
{
TreeNode* tr = new TreeNode(start);
res.push_back(tr);
return res;
}
for(int i = start; i <= end; i++)
{
vector<TreeNode*> l = genTree(start,i-1);
vector<TreeNode*> r = genTree(i + 1,end);
for(int j = 0; j < l.size(); j++)
{
for(int k = 0; k < r.size(); k++)
{
TreeNode* h = new TreeNode(i);
h->left = l[j];
h->right = r[k];
res.push_back(h);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if(n == 0)
return res;
return genTree(1,n);
}
};