【问题标题】:Returning an object pointer from a recursive function met with access violation从递归函数返回对象指针遇到访问冲突
【发布时间】:2020-12-13 17:27:30
【问题描述】:

我创建了一个简单的递归函数,它执行前序遍历以返回与目标字符串匹配的节点。

#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
    string value;
    Node *left, *right;

    Node(string value) {
        this->value = value;
        this->left = NULL;
        this->right = NULL;
    }
};

class Tree {
    public:
    Node* preorder(Node* root, string target) {
        if (root == NULL) return NULL;

        if (root->value == target) {
            return root;
        }

        preorder(root->left, target);
        preorder(root->right, target);
    }
};

int main() {
    Node* a = new Node("a");
    Node* b = new Node("b");
    Node* c = new Node("c");
    Node* d = new Node("d");

    a->left = b;
    a->right = c;
    c->left = d;

    Tree t = Tree();
    Node* found = t.preorder(a, "d");
    cout << found->value << endl;
}

遍历已正确完成,但程序不打印任何内容。在使用 g++ 编译并运行后,我得到了一个[Done] exited with code=3221225477 in 2.038 seconds

我在哪里弄乱了指针?

【问题讨论】:

  • preorder 在块的末尾应该返回什么?

标签: c++ pointers graph binary-tree binary-search-tree


【解决方案1】:

preorder 在递归情况下不返回任何内容。程序的行为是不完善的。

未来提示:使用编译器警告。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多