我正在嘗試編寫一個程序,該程序可以檢測並打印已交換的BST中的兩個節點。在BST中查找交換的節點
在三級樹中,我使用這種方法達到了接近解決方案的程度。
If (!AllSubTreeAreValid())
{
//Nodes swapped on same side of main root node
}
else
{
int max = getMax(root->left);
int min = getMin(root->right);
if(max > root->data || min < root->data)
{
//Nodes swapped on different sides of main root node
//Print max and min values
}
else
{
//No node swappped
}
}
//Helper functions
int GetMaxEle(TreeNode* tree)
{
while(tree->right!=NULL)
{
tree=tree->right;
}
return tree->info;
}
int GetMinEle(TreeNode* tree)
{
while(tree->left!=NULL)
{
tree=tree->left;
}
return tree->info;
}
但上述方法失敗時,我試圖用四級樹測試。
20
15 30
10 17 25 33
9 16 12 18 22 26 31 34
在根節點15的右子樹中,12更大(違例)。
在根節點15的左子樹中,16更大(違例)。
因此,16,12是上述BST中的交換元素。我如何通過該程序找到他們?
getmax和getmin是做什麼的?我不清楚你在問什麼。 – phoxis
@phoxis:getMax和getMin在主根的左右子樹中查找最大和最小元素。 – Cipher
你的意思是:你有一個BST,兩個節點已經「非法」交換(所以你的結構不再是BST了),你想知道那些? –