首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++结构在递归返回nullptr?

C++结构在递归返回nullptr?
EN

Stack Overflow用户
提问于 2019-09-20 13:15:29
回答 2查看 234关注 0票数 0

我在解leetcode 106。我知道如何在这个问题上使用递归。但我对结构体的罪孽感到困惑。通过的版本如下:

代码语言:javascript
复制
/**
 * 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;
    }
};

然后,我改变了另一种方法,使结构无效,如下所示:

代码语言:javascript
复制
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。那么,这两种方式之间有什么不同呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-20 13:34:58

new操作符将动态分配将存储在堆中的内存。第二个版本不能工作,只需创建变量并将其存储在堆栈中。函数调用完成后,所有信息都将从堆栈中弹出,存储在这些内存位置的任何信息都将不再被视为有效。也就是说,return &root在该函数完成后返回无效的地址。

票数 0
EN

Stack Overflow用户

发布于 2019-09-20 13:35:49

您的不同之处在于您已经创建了一个悬吊指针。简而言之,您不应该返回局部变量的地址(通过引用),因为局部变量在超出作用域时会被取消分配。相反,您应该返回root的副本(按值)。因此,不需要&,但是如果树数据不是原始类型的(不是intdouble、...etc),请确保有一个复制构造函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58029131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档