问题:
4.9 BST序列:通过从左到右遍历数组来创建二进制搜索树 并插入每个元素。给定具有不同元素的二叉搜索树,请打印所有可能的 可能导致这棵树的数组。
我尝试按照书中的说明使用c ++编写给定的解决方案,但在运行时崩溃。
未能找到错误,但我认为这与c ++中的reference&有关系。
下面是我的代码:
#include <iostream>
#include<vector>
#include<list>
using namespace std;
class TreeNode{
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v){
val = v; left = nullptr; right = nullptr;
}
};
void weave(vector<list<int>> &, list<int> &, list<int> &, list<int> &);
vector<list<int>>& allSequence(TreeNode *);
vector<list<int>>& allSequence(TreeNode *root){
vector<list<int>> result_seq;
if(!root){
result_seq.push_back(list<int>());
return result_seq;
}
list<int> prefix ;
prefix.push_back(root->val);
vector<list<int>> &leftSeq = allSequence(root->left);
vector<list<int>> &rightSeq = allSequence(root->right);
for(int i = 0; i < leftSeq.size(); i++){
for(int j = 0; j < rightSeq.size(); j++){
vector<list<int>> weaved;
weave(weaved, leftSeq[i], rightSeq[j], prefix);
result_seq.insert(result_seq.end(), weaved.begin(), weaved.end());
}
}
return result_seq;
}
/** Weave lists together in all possible ways. This algorithm works by removing the
head from one list, recursing, and then doing the same thing with the other
list. */
void weave(vector<list<int>> &results, list<int> &first, list<int> &second, list<int> &prefix){
/** One list is empty. Add remainder to [a cloned] prefix and store result. */
if(first.size() == 0 || second.size() == 0){
list<int> result(prefix.begin(), prefix.end());
(first.size()) ? (result.insert(result.end(), first.begin(), first.end())) : (result.insert(result.end(), second.begin(), second.end()));
results.push_back(result);
return;
}
int headFirst = first.front(); first.pop_front();
prefix.push_back(headFirst);
weave(results, first, second, prefix);
prefix.pop_back();
first.push_front(headFirst);
int headSecond = second.front(); second.pop_front();
prefix.push_back(headSecond);
weave(results, first, second, prefix);
prefix.pop_back();
second.push_front(headSecond);
}
int main() {
TreeNode *root = new TreeNode(5);
root->right = new TreeNode(7);
root->left = new TreeNode(3);
vector<list<int>> allSequence_As_list = allSequence(root)
/// print
for(auto i = allSequence_As_list.begin(); i != allSequence_As_list.end(); i++){
for(auto j = (*i).begin(); j!= (*i).end(); j++)
cout<<*j<<" ";
cout<<"\n";
}
}