我無法輸出二叉搜索樹。我必須構建樹,然後將樹中的所有雙精度元素按順序放入一個向量中,然後按順序輸出該向量。我遇到的問題是將其導入矢量並輸出它。當我剛剛輸出樹時,一切都按原樣運行。該向量應該被排序,並且std :: vector * sort()應該返回一個指向向量的指針。我遇到的問題是我遇到了分段錯誤,我不知道爲什麼。任何意見,將不勝感激。這是我的代碼:二進制搜索樹輸出
#include <vector>
struct ordered_set {
private:
class node {
public:
double val;
node* left;
node* right;
node(double v, node* l, node* r): val(v), left(l), right(r) { }
};
node* root;
int size;
public:
ordered_set();
void insert(double x);
std::vector<double>* sort();
std::vector<double>* order(node*);
};
#include <vector>
#include <iostream>
#include "ordered_set.hpp"
ordered_set::ordered_set()
{
root = 0;
size = 0;
}
void ordered_set::insert(double x)
{
node* data = new node(x, 0, 0);
node* parent;
parent = 0;
if(root == 0)
root = data;
else
{
node* curr = root;
while (curr)
{
parent = curr;
if(data->val > curr->val)
curr = curr->right;
else
curr = curr->left;
}
if(data->val < parent->val)
parent->left = data;
else
parent->right = data;
}
++size;
}
std::vector<double>* ordered_set::sort()
{
node* ndptr = root;
return order(ndptr);
}
std::vector<double>* ordered_set::order(node* top)
{
node* curr = top;
std::vector<double>* set;
std::vector<double>::iterator it = set->begin();
if(curr != 0)
{
order(curr->left);
set->insert(it, curr->val);
++it;
order(curr->right);
}
else return set;
}
謝謝你的解釋。在你說完之後,它非常有意義,我說:「不要!」非常感謝! – user870222