-1

我正在尝试使用 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吗?

4

1 回答 1

1

线

data = data;

在构造函数中将参数分配给data参数data,实际上什么都不做。

它应该是

this->data = data;

初始化成员变量data

于 2021-06-19T04:50:50.910 回答