【问题标题】:How to replace information in already existing node, without losing it's children?如何在不丢失子节点的情况下替换现有节点中的信息?
【发布时间】:2019-05-17 09:19:11
【问题描述】:

所以我已经实现了一个二叉搜索树,并且我已经管理了一个有效的插入方法。所有节点都包含有关课程代码、课程名称和课程学分的课程信息。 假设我想插入一个具有相同密钥(课程代码)但课程学分不同的新节点,那么它不会加起来。似乎我的树丢失了我更改的节点的子节点。

我尝试在键相等的情况下写“node”而不是“root”,但是就像我之前说的那样,它会丢失孩子。

public void insert(String courseCode, String courseName, double courseCredits) {
    BSTNode node = new BSTNode(courseCode, courseName, courseCredits);  
    root = insert(root, node);  
}

private BSTNode insert(BSTNode root, BSTNode node) {
    if (root==null) {
        return node;
    } else {
        String currentKey = root.getCourseCode();
        BSTNode left = root.getLeftChild();
        BSTNode right = root.getRightChild();
        if (node.getCourseCode().compareTo(currentKey) < 0) {
            left = insert(left, node);
        } else if (node.getCourseCode().compareTo(currentKey) > 0) {
            right = insert(right, node);  //Ändrade "left" till "right" i parentesen.
        } else {
            return root; 
        }

        root.setChildren(left, right);
        return root;
    }
}

【问题讨论】:

  • 在你问的问题中,“插入一个新节点”。在标题中,您询问编辑和现有节点。首先,您需要编辑图表。第二个你需要编辑节点。请澄清并发布minimal reproducible example
  • 好吧,我的图表是正确的,但如果他们获得相同的密钥(课程代码),我希望能够用新节点“覆盖”现有节点。我只是认为在插入方法中这样做会更容易。
  • 编辑现有节点与插入新节点不同。您只需要一个 BSTNode 类中的 setter 并使用它:node.setCourseCredits(5);。 “我只是认为在插入方法中这样做会更容易”我不会推荐它。让方法只做一件事。
  • 好的,但是为什么不能从插入方法内部呢? (我相信你,我只是想了解)制作这样的二传手最好的方法是什么?
  • 我想我现在可以使用它了,所以谢谢你:)

标签: java insert binary-search-tree


【解决方案1】:

只需替换当前节点的courseNamecourseCredits即可:

...
if (root==null) {
    root.setCourseName(node.getCourseName());
    root.setCourseCredits(node.getCourceCredits());
    return node;
} else {
    ...
    } else {
        root.setCourseName(node.getCourseName());
        root.setCourseCredits(node.getCourceCredits());
        return root; 
    }
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2021-05-10
    • 1970-01-01
    • 2023-03-24
    • 2014-05-04
    • 2023-03-31
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多