簡體   English   中英

二叉樹不接受新節點

[英]Binary tree doesn't accept new node

int main(){
Node *root , *temp , *temp_before;
root = new Node(0 , NULL , NULL , NULL);
temp_before = root;
temp = temp_before->left;
temp = new Node(5 , NULL , NULL , NULL);
temp = root->left;
cout<<temp->val;
}

我有一個名為Node的結構,第一個參數是int,其他參數是Node指針。 當我想打印root-> left無效時,運行該程序時將其停止。 我不知道,也許我正在做一件很奇怪的事情,希望它能返回一些東西,但是出了什么問題呢?

有幾件事。 您將需要檢查您的節點是否等於null。 您還應該更新輸出內容。

node = root;
while (node != null) 
{
    count << node;
    node = node->left;

}

讓我們逐行看一下代碼:

struct Node {
    int val;
    Node* left;
    Node* right;
    Node* parent;
    Node(int value, Node* left, Node* right, Node* parent): val(value), left(left), right(right), parent(parent){}
};

void main() {
    Node *root, *temp, *temp_before;
    root = new Node(0, NULL, NULL, NULL); // root points to the newly allocated memory
    temp_before = root; //temp_before also points to that memory
    temp = temp_before->left; // temp points to the left of root, which is null
    // NOTE: at this point, temp isn't connected to the tree, even if you allocate memory with it.
    // You only have pointers ("handles") for those memory blocks but you haven't combined them together yet.
    temp = new Node(5, NULL, NULL, NULL); // This allocated memory for the memory address pointed by temp
    // temp = root->left; //error
    root->left = temp; //correct one
    // Now root->left points to the memory block you allocated with temp
}

當使用指針分配內存時,指針僅指向該內存塊。 除非您手動將它們連接在一起,否則它們不會成為連接的結構。

那是您試圖做的,但是方式錯誤。 可以這樣想:分配內存時,操作系統會為您提供主內存中的空間。 它通過為您提供對該存儲塊的“引用”來做到這一點,以便您可以根據需要使用該存儲塊。 這就是為什么指針也被稱為“句柄”的原因,因為它們是您與內存塊進行交互的方式。

在錯誤的行中,您將句柄重寫為剛剛分配的內存。 執行此操作時,您將無法訪問該內存塊,直到程序執行結束。 這些覆蓋被稱為“內存泄漏”,因為您曾問過但忘記了該內存塊。

當您執行temp = root->left; ,它會用另一個指針(在本例中為NULL )覆蓋您的指針,當您嘗試打印它時,它會給您一個錯誤,稱為null pointer exception ,從名稱中您可以清楚地看到問題:)

當您使要做的事情過於復雜時,這些錯誤就會發生,特別是如果您對內存沒有經驗的時候。 簡化此代碼的方法是:

void main() {
    Node* root = new Node(0, NULL, NULL, NULL); // Allocate root
    root->left = new Node(5, NULL, NULL, NULL); // This line means "add a new node to the left of my root"

    std::cout << root->val << std::endl;
    std::cout << root->left->val << std::endl;
}

如果您在上面的實現中遇到困難,請這樣考慮:

Node* temp = new Node(5, NULL, NULL, NULL);
root->left = temp;

該代碼與main函數中的代碼相同。 這樣想:您正在分配一個內存塊,並使用temp訪問它。 之后,您要將該句柄的信息分配給根的左節點指針。 這樣,即使您不再有temp權限,也可以通過root->left訪問相同的內存塊。

下面的代碼是您如何考慮的。 嘗試考慮一下這兩者之間的區別,一旦弄清楚了,指針將更有意義:

Node* temp = root->left;
temp = new Node(5, NULL, NULL, NULL);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM