[英]Finding the second max element in a binary search tree
I have a problem with finding the second maximum element in a binary search tree. 我在二进制搜索树中找到第二个最大元素时遇到问题。 I do not know why but in some cases my programm crashes or gives incorrect answer (I don't know those cases).
我不知道为什么,但是在某些情况下,我的程序崩溃或给出了错误的答案(我不知道这些情况)。 Help me to find a problem in my algorithm in code below.
在下面的代码中帮助我找到算法中的问题。 Thank you.
谢谢。
#include <iostream>
using namespace std;
struct Node {
Node* right;
Node* left;
int data;
Node* parent;
};
Node* maximum(Node *root){
if (root -> right)
return maximum(root -> right);
else
return root;
}
void insert(Node *root, Node *a){
if (root -> left && root -> data > a -> data)
return insert(root -> left, a);
if (root -> right && root -> data < a -> data)
return insert(root -> right, a);
if (root -> data > a -> data){
root -> left = a;
a -> parent = root;
}
if (root -> data < a -> data){
root -> right = a;
a -> parent = root;
}
}
int main(){
int j = 0;
int n = 0;
Node *root = new Node;
cin >> j;
if (j != 0) {
root -> data = j;
root -> parent = NULL;
root -> left = NULL;
root -> right = NULL;
} else {cout << "0"; return 0;}
while (true){
cin >> j;
if (j == 0) break;
Node *a = new Node;
a -> data = j;
a -> left = NULL;
a -> right = NULL;
a -> parent = NULL;
insert(root, a);
}
if(!max -> parent)
if (max -> left)
cout << maximum(max -> left) -> data;
else
cout << max -> data;
else
if (max -> left && max -> left > max -> parent)
cout << maximum(max -> left) -> data;
else
cout << max -> parent -> data;
return 0;
}
In the following code: 在下面的代码中:
Node* max = maximum(root);
if (max->left){
if (max->parent->data > max->left->data) cout << max->parent->data;
else cout << max->left->data;
} else
cout << max->parent->data;
If your max
turns out to be root
, then max->parent
will be NULL
. 如果您的
max
结果是root
,则max->parent
将为NULL
。 So you should check for NULL
condition before testing it on data
. 因此,您应该在对
data
进行测试之前检查NULL
条件。
Check you are following this Logic :- 检查您是否遵循此逻辑:-
Second max will be in the left subtree of max or its parent. 第二个max将在max或其父元素的左子树中。
If if left-subtree exists then find max of left-subtree which is second highest 如果是否存在left-subtree,则找到第二高的left-subtree的最大值
If if left-subtree does not exist then parent of max is second highest. 如果left-subtree不存在,则max的父级为第二高。
Corner cases 角落案例
1) root is null ie no element. 1)root为null,即没有元素。 No need to check all these.
无需检查所有这些。
2) Root is the only element ie there is only 1 number. 2)根是唯一的元素,即只有1个数字。 So no second highest as parent of root is null.
因此,作为root的父级的第二高位不为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.