在二进制树插入和遍历期间,我得到了分段故障
During binary tree insertion and traversal I get a segmentaion fault
#include <iostream>
struct node {
int val;
node * left, * right;
node(int value) : val(value), left(NULL), right(NULL) {}
};
void insert(node * &root, int val) {
if(!root)
root = new node(val);
else {
if(val <= root->val)
insert(root->left, val);
else
insert(root->right, val);
}
}
void inorder(node *root) {
if(root == NULL)
return ;
inorder(root->left);
std::cout << root->val << " ";
inorder(root->right);
}
int main(){
node *root = NULL;
int arr[] = {7,3,8,6};
for(auto i:arr)
insert(root, arr[i]);
inorder(root);
std::cout << std:: endl;
return 0;
}
使用GCC 5.4.0的Ubuntu 16.04.1上的C 11编译了所有这些该程序给我一个细分错误。但是,当我在树上手动创建新节点时,inorder traversal效果很好。
在您的范围内,当您调用插入insert(root, arr[i])
时,您只需要i
而不是arr[i]
。因此,将其更改为insert(root, i);
。
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串
- 面临分段故障 使用 ffmpeg 读取视频时,因为"pFormatCtx-> streams [i]-> codecpar"的地址0x00
- 在C++中,当指向删除和指向不同对象时,分段故障指针
- 对程序故障进行分段
- 分段故障说明
- 分段故障(核心转储)-不知道为什么
- 分段故障线程
- hiredis SET遇到分段故障
- 分段故障,合并排序算法
- 多线程程序中的分段故障和gdb回溯上的不完整信息
- 到达主C++之前分段故障
- 分段故障核心使用 IF流转储
- 使用向量的移动键盘排列(分段故障)
- 在二进制树插入和遍历期间,我得到了分段故障
- 分段故障在类之间返回整数