![](/img/trans.png)
[英]Why can't I return pointer to a node of my BST tree structure? C++
[英]C++ program implementing tree stops working when a node is inserted and I can't understand why
這是我的代碼。 讀取T之后,程序將讀取第一個輸入數據並停止工作。 消息“ tree.exe中0x00844D30處未處理的異常:0xC0000005:訪問沖突讀取位置0x00000000。” 顯示。 我包括了iostream和stddef.h庫。
class Node{
public:
int data;
Node *left, *right;
Node(int d){
data = d;
left = right = NULL;
}
};
class Solution{
public:
Node* insert(Node* root, int data){
if (root = NULL){
return new Node(data);
}
else{
Node* cur;
if (data <= root->data){
cur = insert(root->left, data);
root->left = cur;
}
else{
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
};
int main(){
Solution myTree;
Node* root = NULL;
int T, data;
cin >> T;
while (T-->0){
cin >> data;
root = myTree.insert(root, data);
}
return 0;
}
條件應該是
如果(root == NULL)
#include <iostream>
#include <stddef.h>
using namespace std;
class Node{
public:
int data;
Node *left, *right;
Node(int d){
data = d;
left = right = NULL;
}
};
class Solution{
public:
Node* insert(Node* root, int data){
if(root == NULL){
return new Node(data);
}
else{
Node* cur;
if (data <= root->data){
cur = insert(root->left, data);
root->left = cur;
}
else{
cur = insert(root->right, data);
root->right = cur;
}
cur->left=cur->right=NULL;
return root;
}
}
};
int main(){
Solution myTree;
Node* root = NULL;
int T, data;
cin>>T;
while (T-->0){
cin>>data;
root = myTree.insert(root, data);
}
return 0;
}
如果這將始終進入其他部分。 因為您將NULL分配給變量root,然后檢查該值。 它應該是root == NULL
if (root = NULL){
return new Node(data);
}
else{
Node* cur;
if (data <= root->data){
cur = insert(root->left, data);
root->left = cur;
}
else{
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.