有没有大佬能告诉我,为什么下面代码中两个insert函数的区别(被注释了的是错误的),为什么会出错啊。
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Node{
int value;
Node*left;
Node*right;
Node(int v,Node* l,Node* r){
value=v;
left=l;
right=r;
}
Node(){
value=0;
left=NULL;
right=NULL;
}
};
//void insert(Node*root,int value){
// if(root==NULL){
// root = new Node(value,NULL,NULL);
// return;
// }
// if(value<root->value){
// insert(root->left,value);
// }
// if(value>root->value){
// insert(root->right,value);
// }
//}
void insert(Node*root,int value){
if(value<root->value){
if(root->left==NULL){
root->left = new Node(value,NULL,NULL);
}else{
insert(root->left,value);
}
}
if(value>root->value){
if(root->right==NULL){
root->right = new Node(value,NULL,NULL);
}else{
insert(root->right,value);
}
}
}
void pre(Node*root){
cout<<root->value<<" ";
if(root->left){
pre(root->left);
}
if(root->right){
pre(root->right);
}
}
void bew(Node* root){
if(root->left){
bew(root->left);
}
cout<<root->value<<" ";
if(root->right){
bew(root->right);
}
}
void lat(Node* root){
if(root->left){
lat(root->left);
}
if(root->right){
lat(root->right);
}
cout<<root->value<<" ";
}
int main(){
int n,i,j,value;
while(cin>>n){
Node* root = new Node();
cin>>value;
root->value=value;
root->left=NULL;
root->right=NULL;
for(i=1;i<n;i++){
cin>>value;
insert(root,value);
}
pre(root);
cout<<"\n";
bew(root);
cout<<"\n";
lat(root);
cout<<"\n";
}
return 0;
}
在你这个代码,root 为 NULL时,root->left,root->right都是NULL。但是root 不为 NULL时,root->left,root->right也可能是NULL。
因为你注释掉的代码没判断root->left,root->right是否是NULL,跟开空间,如果是null你把它递归了,就会执行
// if(root==NULL){
// root = new Node(value,NULL,NULL);
// return;
// }
这里就回归到,传指针给函数,想通过函数new 新内存的问题。这就要传指针的指针了。
(https://blog.csdn.net/pengshengli/article/details/85319184 "")
需要用二级指针。调用的时候记得也传二级指针。
void insert(Node**root,int value){
if(*root==NULL){
*root = new Node(value,NULL,NULL);
return;
}
if(value<(*root)->value){
insert(&(*root)->left,value);
}
if(value>(*root)->value){
insert(&(*root)->right,value);
}
}
参考代码:
https://gitee.com/shallwing/C-3P/blob/master/DataStructure-OS/DataStructure/tree/sortTree.cpp