从遇到访问冲突的递归函数返回对象指针
Returning an object pointer from a recursive function met with access violation
我创建了一个简单的递归函数,该函数对 return 与目标字符串匹配的节点执行前序遍历。
#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
在递归情况下 return 没有任何作用。程序的行为未完善。
未来提示:使用编译器警告。
我创建了一个简单的递归函数,该函数对 return 与目标字符串匹配的节点执行前序遍历。
#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
在递归情况下 return 没有任何作用。程序的行为未完善。
未来提示:使用编译器警告。