[英]Finding the second max element in a binary search tree
我在二進制搜索樹中找到第二個最大元素時遇到問題。 我不知道為什么,但是在某些情況下,我的程序崩潰或給出了錯誤的答案(我不知道這些情況)。 在下面的代碼中幫助我找到算法中的問題。 謝謝。
#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;
}
在下面的代碼中:
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;
如果您的max
結果是root
,則max->parent
將為NULL
。 因此,您應該在對data
進行測試之前檢查NULL
條件。
檢查您是否遵循此邏輯:-
第二個max將在max或其父元素的左子樹中。
如果是否存在left-subtree,則找到第二高的left-subtree的最大值
如果left-subtree不存在,則max的父級為第二高。
角落案例
1)root為null,即沒有元素。 無需檢查所有這些。
2)根是唯一的元素,即只有1個數字。 因此,作為root的父級的第二高位不為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.