我正在尝试使用 cpp 在 BST 中插入数据。我使用了以下代码:
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){// Constructor...
data = data;
left = NULL;
right = NULL;
}
};
void Pre_Order_Trav(Node* Root){
if(Root==0) return;
cout << Root->data << " ";
Pre_Order_Trav(Root->left);
Pre_Order_Trav(Root->right);
}
Node* Get_New_Node(int data){
Node* temp;
temp = new Node(data);
//temp-> data = data; *******************************Watch Here****************
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* Insert(Node* Root,int data){
//cout << "Inserting: " << data<<"\n";
if(Root == NULL){
Root = Get_New_Node(data);
}
else if(data <= Root->data){
Root->left = Insert(Root->left,data);
}
else{
Root->right = Insert(Root->right,data);
}
return Root;
}
int main(){
int n,x;
//cout << "Enter the size of data: ";
//cin >> n;
cout << "\n";
cout << "Enter data: ";
Node* Root = NULL;
Root= Insert(Root,11);
while(cin >>x) Insert(Root,x);
cout << "\n";
Pre_Order_Trav(Root);
}
Node 类有一个构造函数,它将给定的数据分配给 data 并将 NULL 分配给左右。当“Watch Here”行被评论时,我无法遍历树,但是当它被取消评论时,我能够成功地遍历。不是temp = new Node(data)
一样temp->data = data
吗?