【问题标题】:insert function in BinarySearchTree (Java)BinarySearchTree (Java) 中的插入函数
【发布时间】:2021-01-15 13:18:41
【问题描述】:
 public void insert(String word,String def){
    Node newNode = new Node(word, def);
    if(root==null){
        root=newNode;
    }
     Node p, q ;          
    p = q = root ;      
    while (q != null){  
        p = q ;  
        int c = word.compareToIgnoreCase(p.getWord());
        if (c < 0) {
            q = p.getLeft() ; 
        }
        else{
            q = p.getRight() ;
        }
    }
    int c = word.compareToIgnoreCase(p.getWord());
    if (c < 0) {
        p.setLeft(newNode);
    }
    else{
        p.setRight(newNode);
    }
    
}

我编写这段代码是为了在二叉搜索树中插入节点,但它没有按计划工作。

无限运行后进入根和根后一个节点。 我找不到任何解决方案。

【问题讨论】:

  • 如果您想在树为空时将新节点作为根插入,我认为您在 if(root==null) 中缺少 return 语句。
  • 不一定是解决方案,但您不应该从if (root == null) 返回或将方法的其余部分放在else 块中吗?
  • @Slaw yk 你已经解决了问题
  • @Slaw idk 为什么我一开始没有想到这个。非常感谢。

标签: java data-structures tree binary-tree binary-search-tree


【解决方案1】:
    public void insert(String word,String def){
        Node newNode = new Node(word, def);
        if(root==null){
            root=newNode;
        }else{
         Node p, q ;
        p = q = root ;
        while (q != null){
            p = q ;
//            int c = word.compareToIgnoreCase(p.getWord());
            if ( word.compareToIgnoreCase(p.getWord())<0) {
                q = p.getLeft() ; 
                
            }
            else{
                q = p.getRight() ;
                
            }
        }
//        int c = word.compareToIgnoreCase(p.getWord());
        if (word.compareToIgnoreCase(p.getWord())<0) {
            p.setLeft(newNode);
        }
        else{
            p.setRight(newNode);
        }
        } 
    }

我通过将我的代码放入 if else 中进行了尝试,现在它运行良好。 @slaw 帮我解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多