我的isdup函数将根作为主函数的树,并搜索树中是否存在重复的值。到目前为止,如果在根目录和其他任何地方存在任何重复的值,则所有返回的都是真值。但是,如果树在root-> left和root-> left-left中具有重复的值,则该函数返回false,并且我不知道为什么递归函数中的逻辑错误。
#include "pch.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
node* parent;
node(int newdata):data(newdata){
left = nullptr; right = nullptr; parent = nullptr;
}
};
bool searchit(node*root, int value) {
if (root == nullptr)
return false;
if (value == root->data) return true;
bool left = searchit(root->left, value);
if (left) return true;
bool right= searchit(root->right, value);
return right;
}
bool isdup(node* root) {
if (root != nullptr) {
if (searchit(root->left, root->data))return true;
if (searchit(root->right, root->data))return true;
return isdup(root->left) || isdup(root->right);
}
else return false;
}
void print(node *root) {
if(root!=nullptr){
print(root->left);
cout << root->data;
print(root->right);
}
}
int main() {
node* root = new node(1);
root->left = new node(2);
root->right = new node(4);
root->left->left = new node(4);
print(root);
cout << endl;
if (isdup(root))cout << "Yes, there is duplicated value in the tree" << endl;
else cout << "no, there is no duplicated value in the tree" << endl;
}
答案 0 :(得分:0)
在isdup中,前两个searchit不会返回任何内容(第一次),因为它会查找根数据... 然后,左和右充当根,在左(作为)根下方找不到重复项,就像在右(作为)根下方情况一样。左,右根真的不相关