代码之家  ›  专栏  ›  技术社区  ›  user16218933

我想用迭代法在二叉搜索树中搜索值

  •  0
  • user16218933  · 技术社区  · 4 年前

    您好,我编写此方法是为了在二进制搜索树中搜索值,但无论是否在我的bst中找到该值,它总是返回false。有人能告诉我我的错误是什么,我怎样才能改正它吗。

        public boolean search(int key) {
        BinaryTreeNode subRoot = null;
              
            while (subRoot != null)  
            {  
                 
                if (key > subRoot.getData()) {
                    root = subRoot.getRight();  
                }
                 
                else if (key < subRoot.getData())  
                    root = subRoot.getLeft();  
                else
                    System.out.println("Searching for " + key + ": found");
                    return true; 
            }  
            System.out.println("Searching for " + key + ": NOT found");
            return false;  
        
    }
    
    2 回复  |  直到 4 年前
        1
  •  0
  •   David Almeida    4 年前

    没有更多的投入这是我能做的一切。 一开始你忘了给root分配subRoot。 在这里,将值分配给循环中的根,这将导致数据丢失,很可能是一个无限循环。 另外,else语句没有brakets,因此如果您进入循环,它将始终返回true。

    public boolean search(int key) {
    BinaryTreeNode subRoot = root;
          
        while (subRoot != null)  
        {  
             
            if (key > subRoot.getData()) 
                subRoot = subRoot.getRight();             
            else if (key < subRoot.getData())  
                subRoot = subRoot.getLeft();  
            else{
                System.out.println("Searching for " + key + ": found");
                return true;
            } 
        }  
        System.out.println("Searching for " + key + ": NOT found");
        return false;  
    
    }
    
        2
  •  0
  •   Cezar Todirisca    4 年前

    问题是,在while循环之前用null初始化subRoot,因此当检查条件时,它将始终为false,因此将进入函数的末尾