的左视图我具有如下面通过自己初始化树: -错误而表示树
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct node{
int data = 0;
node* left = nullptr;
node* right = nullptr;
};
void construct(struct node* &tree)
{
tree->data = 66;
tree->left = new node;
tree->right = new node;
tree->left->left = new node;
tree->left->left->left = new node;
tree->left->left->right = new node;
tree->left->left->left->left = new node;
tree->left->left->left->right = new node;
tree->left->left->left->right->right = new node;
tree->right->right = new node;
tree->right->left = new node;
tree->right->left->left = new node;
tree->right->left->right = new node;
tree->right->left->right->left = new node;
tree->left->data = 50;
tree->left->left->data = 46;
tree->left->left->left->data = 89;
tree->left->left->right->data = 37;
tree->left->left->left->left->data = 53;
tree->left->left->left->right->data = 81;
tree->left->left->left->right->right->data = 86;
tree->right->data = 72;
tree->right->left->data = 78;
tree->right->right->data = 71;
tree->right->left->left->data = 87;
tree->right->left->right->data = 35;
tree->right->left->right->left->data = 17;
}
void show_tree_view(struct node* const &tree, string view)
{
queue<struct node*> box;
box.push(tree);
cout << box.front()->data << " ";
int size = box.size();
while(!box.empty())
{
for(int i = 0; i < size; ++i)
{
struct node* current = box.front();
box.pop();
if(current->left != nullptr) box.push(current->left);
if(current->right != nullptr) box.push(current->right);
}
size = box.size();
if(view == "left") cout << box.front()->data << " ";
if(view == "right") cout << box.back()->data << " ";
}
cout << endl;
}
int main()
{
struct node* tree = new node;
construct(tree);
/*int height = calculate_height_by_recursion(tree);
cout << "height with recursion : " << height << endl;
height = calculate_height_without_recursion(tree);
cout << "height without recursion : " << height << endl;*/
cout << "Left view of tree is : ";
show_tree_view(tree, "left");
//cout << "Right view of tree is : ";
//show_tree_view(tree, "right");
return 0;
}
当运行上述程序中,对于所有的其它功能(我已删除,由于大的代码)的工作没问题,但是用来显示左右视图的功能不起作用。它既不显示任何错误。当我运行该程序,它显示了段故障: - 输出 -
[email protected]:~/Ujjal$ ./simple_tree
Segmentation fault (core dumped)
我调试的上方,但未能赶上错误。建议是必需的。
所以你还没有准备好调试这个疯狂的代码?此外,无论在哪个节点上都有'struct'的状态, C++不是'C'。 – PaulMcKenzie
@ PaulMcKenzie这是因为当我编写计算高度的代码(使用级别顺序遍历)时,它工作正常,然后复制粘贴相同的代码显示核心转储。这真的很烦人,你知道;) –