【发布时间】: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