0
struct node
{
    int data;
    node* left;
    node* right;
};

int secondlargest(struct node* a)
{
    while(a->right != NULL){
        secondlargest(a->right);
    }
    return a->data;
}

我无法追踪我在哪里犯了错误以及为什么它没有退出 while 循环。

4

2 回答 2

1

您的错误是您不应该使用 while 而是使用 if 因为它是递归的,但是您希望函数返回什么?最后一个成员的数据?如果是这样,它应该是这样的:

int secondlargest(struct node* a) {
   if(a == NULL) return -1;
   secondlargestr(a);
}

int secondlargestr(struct node* a) {
   if(a->right!=NULL) return secondlargest(a->right);
   return (a->data);
}
于 2011-03-04T01:41:48.910 回答
0

如果您坚持使用递归版本,请将 while 更改为 if。

int secondlargest(node* a)
{
    if(a == null){
        // if the first node is already NULL
        return -1;
    }
    if(a->right == NULL){
        return a->data;
    }else{
        return secondlargest(a->right);
    }
}

递归基础:

  • 必须有基本情况
  • 递归分解问题大小

如果你想要迭代方式:

int secondlargest(node* a)
{
    node* temp = a;
    int data = -1;
    while(temp != null){
        data = temp->data;
        temp = temp->right;
    }
    return data;
}
于 2011-03-04T01:42:57.550 回答