c++ - 查找二叉搜索树是否有重复值
问题描述
对于二叉搜索树,查看树是否具有重复值。我采用了这种邮购方式。
我的目标是保留当前节点的值,然后使用其他函数遍历树以查看是否有与该当前值匹配的值,如果找到任何重复值,它会带来“真实值”。我选择使用递归,因为它似乎更容易跟踪。但是当我运行程序时没有输出。
#include "pch.h"
#include <iostream>
using namespace std;
class BSTNode {
public:
int data;
BSTNode* left;
BSTNode* right;
BSTNode() {};
};
BSTNode* newnode(int newdata) { BSTNode *curr = new BSTNode; curr->data = newdata; curr->left = curr->right = nullptr; return curr; }
void print(BSTNode* root) {
if (root != nullptr) {
print(root->left);
cout << root->data << endl;
print(root->right);
}
}
bool checking(BSTNode* parent, int val) {
if (val == parent->data){
bool left = checking(parent->left, val);
bool right = checking(parent->right, val);
return left||right;
}
else
return false;
}
bool assist(BSTNode* parent) {
if (parent != nullptr) {
assist(parent->left);
assist(parent->right);
return checking(parent, parent->data);
}
else return false;
}
int main() {
BSTNode *test = newnode(1);
test->left=newnode(2);
test->right=newnode(3);
test->left->left=newnode(2);
test->right->right=newnode(5);
print(test);
if (assist(test))
cout << "There is duplicated" << endl;
else
cout << "There is no duplicated" << endl;
return 0;
}
解决方案
您的检查功能应如下所示:
bool checking(BSTNode* parent, int val) {
if(parent == nullptr) // point 1
return false;
if (val == parent->data){ // point 2
return true;
}
else{
bool left = checking(parent->left, val);
bool right = checking(parent->right, val);
return left||right;
}
}
您的辅助功能应如下所示:
bool assist(BSTNode* parent) {
if (parent != nullptr) {
if(checking(parent->left, parent->data)) return true; // point 3
if(checking(parent->right, parent->data)) return true;
return assist(parent->left)||assist(parent->right); // point 4
}
else return false;
}
您需要检查空值。
如果
val
相同,为什么还要检查?停下来您需要检查左右子树中节点的值。
为子节点递归它
推荐阅读
- php - 如何使用 PHP 和 VUEJS 将 2 个文件从 2 个单个输入文件上传到数据库
- python - 如何从 xlwings 调用 Excel 函数
- c# - 无法在 Unity 中将路径点与线渲染器连接起来
- apache-spark - 导入 org.apache.spark.streaming.kafka._ 无法解析符号 kafka
- reactjs - 为什么我在控制台中收到这样的警告,即标签按钮在此浏览器中无法识别
- ios - 架构 arm64 的未定义符号,似乎只是随机发生在某些使用 cocoapods 的第三方框架中
- sed - 如何使用 sed 从 CSV 文件中删除动态字符串?
- git - git中损坏的文件和树
- c# - 使用 .Net 中的 IAmsiStream 会导致 AccessViolationException
- javascript - 在子标题之间选择相邻的兄弟姐妹作为单独的组?