问题描述
我创建了一个简单的递归函数,该函数执行预遍历以返回与目标字符串匹配的节点。
#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
在递归情况下不返回任何内容。该程序的行为是不确定的。
将来的提示:使用编译器警告。