我接到了这个电话
productTree.displayNode(productTree.newsearchTree(search, productTree.Root()));
调用这些功能
void Tree::displayNode(Node* node) {
if (node != NULL) {
cout << node->productdata << endl;
}
}
Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
newsearchTree(search, node->left);
if (search == node->productdata.getName()) {
return node;
}
newsearchTree(search, node->right);
}
}
Node* Root() { return root; };
在尝试显示返回的节点时会产生垃圾输出。
然而,我可以通过这种方式遍历我的树并显示它:
这个电话:
productTree.Inorder(productTree.Root());
功能:
void Tree::Inorder(Node* node) {
if (node != NULL) {
Inorder(node->left);
displayNode(node);
Inorder(node->right);
}
}
我感到困惑的是它们有何不同?
编辑:感谢您的帮助,我修改了以下代码,现在工作正常:
Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
newsearchTree(search, node->left);
if (search == node->productdata.getName()) {
return node;
}
newsearchTree(search, node->right);
}
return NULL;
}
void Tree::displayNode(Node* node) {
if (node != NULL) {
cout << node->productdata << endl;
}
else if (node == NULL) {
cout << "Product not found" << endl;
}
}
是的,那还是坏了。这终于修好了我相信:
Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
if (search == node->key) {
return node;
}
if (search < node->key) {
return newsearchTree(search, node->left);
}
else {
return newsearchTree(search, node->right);
}
}
else return NULL;
}
答案 0 :(得分:0)
让我在内联添加注释,以明确你的Tree :: newsearchTree做了什么。
Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
newsearchTree(search, node->left); // burn CPU but leaves no side effect
if (search == node->productdata.getName()) {
return node; // return node only if the root node equals 'search'
}
newsearchTree(search, node->right); // burn CPU without side effect
}
// In majority of the cases (root node != 'search'): return nothing.
}
因为通常newsearchTree()什么都不返回,所以当你调用productTree.displayNode(productTree.newsearchTree(...))时,你基本上都会打印垃圾。