簡體   English   中英

C++ 結構體遞歸返回 nullptr ?

[英]C++ Struct in recursion return nullptr ?

我正在解決leetcode 106 我知道如何在這個問題中使用遞歸。 但是我對結構的初始化感到困惑。 通過的版本如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int len = inorder.size();
        if (inorder.empty() && postorder.empty())
            return nullptr;
        return buildTree(inorder, 0, len - 1, postorder, 0, len - 1);
    }

    int getIndex (vector<int> order, int key)
    {
        int i = 0;
        for(int n: order)
        {
            if (n == key)
                break;
            i++;
        }
        return i;
    }

    TreeNode* buildTree(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe)
    {
        if (is > ie || ps > pe)
            return nullptr;
        TreeNode* root = new TreeNode(postorder[pe]);
        int index = getIndex(inorder, postorder[pe]);
        //cout<< index <<" "<<postorder[pe]<< endl;
        root->left = buildTree(inorder, is, index - 1, postorder, ps, ps + index - is - 1);
        root->right = buildTree(inorder, index + 1, ie, postorder, pe - ie + index,pe - 1);
        return root;
    }
};

然后我改變了另一種方式來初始化結構,如下:

TreeNode* buildTree(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe)
{
    if (is > ie || ps > pe)
        return nullptr;
    struct TreeNode root(postorder[pe]);
    int index = getIndex(inorder, postorder[pe]);
    //cout<< index <<" "<<postorder[pe]<< endl;
    root.left = buildTree(inorder, is, index - 1, postorder, ps, ps + index - is - 1);
    root.right = buildTree(inorder, index + 1, ie, postorder, pe - ie + index,pe - 1);
    //cout<< root.val << " " << root.right << " " << root.left <<endl;
    return &root;
}

這個版本總是返回 nullptr。 那么這兩種方式有什么問題以及有什么區別?

new運算符將動態分配 memory 將存儲在堆上 第二個不起作用的版本只是創建變量並將其存儲在堆棧中。 在 function 調用完成之后,所有信息將從堆棧中彈出,並且存儲在這些 memory 位置的任何內容將不再被視為有效。 即說return &root在 function 完成后返回一個無效地址。

您所做的不同之處在於您創建了一個Dangling Pointer 簡而言之,您不應該返回局部變量的地址(通過引用),因為局部變量在超出 scope 時會被釋放。 相反,您應該返回root的副本(按值)。 因此,不需要& ,但如果您的樹數據不是原始類型(不是intdouble等),請確保您有一個復制構造函數

暫無
暫無

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

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