2017-02-09 126 views
0
int secondSmallestInBST(struct node * tNode) { 
if(tNode==NULL || (tNode->left==NULL && tNode->right==NULL)) // case 1 and 2 
    exit; 
if(tNode->left == NULL){      // case 3 
    tNode=tNode->right; 
    while(tNode->left!=NULL){ 
     tNode=tNode->left; 
    } 
    return tNode->data; 
}              // general case. 
node * parent=tNode,* child = tNode->left; 
while(child->left!=NULL){ 
    parent = child; 
    child = child->left; 
} 
return parent->data; 

}在二叉搜索樹

不是每個測試用例通過了我的代碼中發現第二個最小元素。如果我的代碼中缺少任何測試用例,建議我。我只是在二叉搜索樹中找到第二小元素。

int secondSmallestInBST(struct node * tNode) { 
if(tNode==NULL || (tNode->left==NULL && tNode->right==NULL)) // case 1 and 2 
    exit; 
if(tNode->left == NULL){      // case 3 
    tNode=tNode->right;      // find smallest in right bst. 
    while(tNode->left!=NULL){ 
     tNode=tNode->left; 
    } 
    return tNode->data; 
}              // general case. 
if(tNode->left->left==NULL && tNode->left->right!=NULL){ //missed case. 
    tNode=tNode->left->right; 
    while(tNode->left!=NULL){ 
     tNode=tNode->left; 
    } 
    return tNode->data; 
} 
node * parent= tNode; 
node * child = tNode->left; 
while(child->left!=NULL){ 
    parent = child; 
    child = child->left; 
} 
return parent->data; 

}

//仍下落不明在此代碼一些測試用例。

+0

[該程序的完整源代碼(http://ideone.com/m6zu8D) 這裏是完整的代碼。 –

+0

請將編程語言添加爲標記,如果可以,請提供失敗測試的示例 – MrPk

+0

@MrPk我在問我是否忘記了我的代碼中的一些測試用例。 –

回答

1

測試對於這種情況 - 3 6 2 3 樹看起來就像這樣:

6 
/
    2 
    \ 
    3 

你正在做的方式,答案就會出來是6,而這是3

+0

哦,明白了。 謝謝:) –

+0

我已經將您的測試用例添加到我的代碼中,即使它已被部分接受。 –

0

`

int Successor(Node* root){ 
    while(root->left){ 
    root = root->left; 
    } 
    return root->data; 
} 

int Second_Minimum(Node* root){ 
    // make sure tree is not empty 
    if(!root) 
    return -1; 
    // previous node takes before the last left node 
    Node* previous = root; 
    // check left node first for smallest key 
    if(root->left){ 
    while(root->left){ 
     previous = root; 
     root = root->left;  // 6 
    }       // /
    // checks for the case ----> 2 
    if(!root->right)   // \ 
     return previous->data; // 3 
    } 
    // Go for minimum successor if exists 
    if(root->right) 
    return Successor(root->right); 
    // checked left and right branch root is on his own 
    return -1; 
} 

`