【问题标题】:BinarySearchTree insert methodBinarySearchTree 插入方法
【发布时间】:2015-11-21 22:10:15
【问题描述】:

我正在尝试使用递归来为 BST 编写插入方法。

 public void insert(DictEntry data) throws BSTException {
     if (find(data.getPosition()) == data){
         throw new BSTException();
     }
     else {
         if (current == null){
             root.setRoot(data);
     }
         else {
             while(current != null){
                 if (data.getPosition().compareTo(root.getRoot().getPosition()) < 0){
                     current = current.getLeft();
                 }
                 else{
                     if (data.getPosition().compareTo(root.getRoot().getPosition()) > 0){
                         current = current.getRight();
                     }
                     else
                         ;
                 }
                 insert(data);
             }
         }

     }
 }

但我不知道由于某种原因测试用例总是失败。 有人可以帮我解决吗?

【问题讨论】:

    标签: java insert binary-search-tree


    【解决方案1】:

    这段代码有几个问题:

    1. 您将递归实现与迭代实现混为一谈。在函数“insert”中调用“insert(data)”来使用递归时,不需要“while”循环
    2. 当您最终达到递归if (current == null){ 的基本情况时,您在根处插入?您应该在“当前”处插入,因为这是您发现为空且匹配顺序的子树
    3. 您总是将数据与“根”而不是“当前”进行比较

    其他问题:

    • 您的代码格式错误(第一个“else”之后的“}”应该缩进更多,“else ;”是不必要的)
    • 您正在通过更新函数外部的变量来使用递归:“当前”。这可能有效,但这是一种糟糕的风格。你的方法应该看起来像public void insert(DictEntry data, BSTNode node),你从insert(data, root)开始,然后递归调用insert(data, node.getLeft()insert(data, node.getRight()

    【讨论】:

    • 感谢您指出我的问题。对于这种方法,构造函数是固定的,即“public void insert(DictEntry data) throws BSTException”(我希望我能有 insert(DictEntry data, BSTNode node))...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多