You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义BST(Roster)中,查询修读指定课程学生的方法调试求助

解决二叉搜索树中打印指定课程学生的问题

嘿,我来帮你搞定这个头疼的作业问题!你提到问题出在printCourseHelper()的if条件判断部分,那咱们就从最常见的坑开始排查,一步步解决:

首先,确认BST的遍历逻辑是否正确

因为你要找所有修读指定课程的学生,不管他们的ID在BST的哪个分支,必须完整遍历整个树,不能因为当前节点的学生没修这门课就跳过左右子树。正确的遍历框架应该是这样的(以中序遍历为例,顺序不影响结果,只要全覆盖就行):

private void printCourseHelper(RosterNode node, String targetCourse) {
    if (node == null) return;
    
    // 先遍历左子树
    printCourseHelper(node.left, targetCourse);
    
    // 检查当前学生的课程列表(这部分是重点!)
    checkAndPrintStudent(node.student, targetCourse);
    
    // 再遍历右子树
    printCourseHelper(node.right, targetCourse);
}

重点:课程匹配的if判断最容易踩的坑

你说的if条件问题,大概率是这几个常见错误:

1. 用==比较字符串,而不是equals()

Java里String是对象,==比较的是两个字符串的内存引用,不是内容!比如你写了:

if (currentCourse.courseName == targetCourse) { ... }

这会导致即使课程名称内容一样,只要是不同的String对象,判断就会失败。必须换成:

// 严格匹配大小写
if (currentCourse.courseName.equals(targetCourse)) { ... }

// 如果需要忽略大小写(比如"Math"和"math"都算匹配)
if (currentCourse.courseName.equalsIgnoreCase(targetCourse)) { ... }

2. 课程链表遍历不完整

检查你是否从头遍历到了链表的末尾,有没有提前跳出循环或者忘记移动指针的情况。比如正确的遍历逻辑应该是:

CourseNode temp = student.courseListHead;
while (temp != null) {
    if (temp.courseName.equals(targetCourse)) {
        // 找到后打印,然后可以break终止循环
        System.out.println("Student ID: " + student.id);
        break;
    }
    temp = temp.next; // 别忘了移动指针!否则会陷入死循环
}

3. 误判匹配状态

比如你可能在找到课程后没有正确标记状态,导致即使匹配成功也没触发打印。可以用一个布尔变量记录是否找到:

boolean hasCourse = false;
CourseNode temp = student.courseListHead;
while (temp != null) {
    if (temp.courseName.equals(targetCourse)) {
        hasCourse = true;
        break;
    }
    temp = temp.next;
}
if (hasCourse) {
    // 打印完整的学生信息,比如ID、课程成绩
    System.out.println("Student: " + student.id + " | Course: " + targetCourse + " | Grade: " + temp.grade);
}

调试小技巧

如果还是找不到问题,可以加一些调试打印辅助排查:

  • 在遍历BST的每个节点时,打印当前学生的ID,确认所有学生都被遍历到了;
  • 在课程循环里,打印每个课程的名称和目标课程对比,看看比较逻辑是否生效;
  • 打印布尔变量hasCourse的值,确认匹配状态是否正确。

内容的提问来源于stack exchange,提问作者Devin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:27:08