在二叉搜索树中找到第二个最小元素

问题描述 投票:0回答:2
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;

}

//仍然缺少此代码中的一些测试用例。

data-structures tree binary-tree binary-search-tree
2个回答
1
投票

测试此案例 - 3 6 2 3.树将如下所示:

    6
   /
  2
   \
    3

你的方式,答案将是6,而它是3。


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;
}

`

© www.soinside.com 2019 - 2024. All rights reserved.