返回状态后,功能不会结束

Function does not end after return placed in condition

本文关键字:结束 功能 状态 返回      更新时间:2023-10-16

这里是节点定义:

Node::Node(int value, Node* left, Node* right) {
this->value = value;
this->left = left;
this->right = right;
}
int Node::getValue() const {
return value;
}
Node* Node::getLeft() const {
return left;
}
Node* Node::getRight() const {
return right;
}

这里的函数包含:

static bool contains(const Node& root, int value)
{
cout << "Root value: " << root.getValue() << endl;
if(root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
else if(root.getLeft() != NULL)
{
cout << "Left tree: " << endl;
contains(*(root.getLeft()), value);
}
else if(root.getRight() != NULL)
{
cout << "Right tree: " << endl;
contains(*(root.getRight()), value);
}
cout << "End" << endl;
return false;
}

现在我使用这个函数:

Node n1(1, NULL, NULL);
Node n3(3, NULL, NULL);
Node n2(2, &n1, &n3);
cout << "Contains? " << contains(n2, 1) << endl;

此 1 值位于左侧子树中。它显示"您输入了",无论如何都会转到显示 0 的函数末尾作为结果。为什么它不显示 1(true(?我错过了什么?

您缺少一些返回语句。

cout << "Root value: " << root.getValue() << endl;
if(root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
else if(root.getLeft() != NULL)
{
cout << "Left tree: " << endl;
contains(*(root.getLeft()), value); // no return here 
}
else if(root.getRight() != NULL)
{
cout << "Right tree: " << endl;
contains(*(root.getRight()), value); // and no return here
}
cout << "End" << endl;
return false;

它检查树是否在某处包含值,但 nether 将结果传递给外部世界。将其更改为

if (root.getValue() == value)
{
cout << "You entered." << endl;
return true;
}
auto left = root.getLeft();
if (left)
{
cout << "Checking Left tree: " << endl;
if (contains(*left, value))
return true;
}
auto right = root.getRight();
if (right)
{
cout << "Checking Right tree: " << endl;
if (contains(*right, value))
return true;
}
cout << "End" << endl;
return false;

它应该有效。