【问题标题】:BST insert(root, value) recursive methodBST insert(root, value) 递归方法
【发布时间】:2020-09-19 08:29:07
【问题描述】:

编辑:我已经想通了 - 放弃了这个设计并重新开始,它成功了!谢谢你的建议。

我正在做 BST 算法作业,但我绝望地坚持使用插入方法。我在网上找到的所有资源都有一个与我创建的类似的版本,但我没有通过我们教授给我们的 JUnit 测试。我可以传递基本情况(root.payload == 值的空根和二叉树)。不过,我似乎无法通过下一个测试。这是我的 insert(root, value) 方法的代码:

public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (root.payload.equals(value)) {
        return root;
    } else if (value < root.payload) {
        return root.left = insert(root.left, value);
    } else {
        return root.right = insert(root.right, value);
    }
    return root;
}

最终返回的是 original 根节点,但据我了解,最后返回的值应该是我的新节点。我查看了我的教科书和一些在线资源,它们都与这个设计非常相似,所以我很困惑为什么它不起作用。我尝试了其他一些设计,但最终都是 NullPointerException。除了检查节点的有效负载之外,提供给我们的 JUnit 测试还验证我们是否将节点插入到了正确的位置。我没有通过这两项测试。这是我们使用递归的第一个任务,所以我还是很陌生。任何指导将不胜感激!

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:

    如果您希望方法的返回值是新插入的节点,则还必须在 elseIf 子句中添加 return 语句,以便在递归堆栈展开时返回新创建的节点。检查下面的代码

    public static Node<Integer> insert(Node<Integer> root, Integer value) {
    if (root == null) {
        root = new Node<>(value);
    } else if (value <= root.payload) {
        return root.left = insert(root.left, value);   // add a return here
    } else {
       return  root.right = insert(root.right, value);  // add a return here
    }
    return root;
    

    }

    【讨论】:

    • 感谢您的建议!我在以前的迭代中尝试过,结果是我最终未能通过早期的一项测试。我将更新上面的代码以反映更改。我仍然通过了我的基本案例,但在尝试插入叶节点时失败了。
    【解决方案2】:
    public static Node<Integer> insert(Node<Integer> root, Integer value) {
        if (root == null) {
            root = new Node<>(value);
        } else if (value < root.payload) {
             root.left = insert(root.left, value);
        } else if (value > root.payload) {
             root.right = insert(root.right, value);
        }
        return root;
    }
    

    这将在正确的位置添加值并返回根。您可以打印树进行检查

    【讨论】:

    • 感谢您的回复。这个版本的代码仍然没有通过测试。当我检查返回的节点的有效负载时,它是原始根节点的有效负载,而不是插入节点的有效负载。
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 2020-11-18
    • 2013-11-26
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多