繁体   English   中英

如何在不使用递归方法的情况下找到二叉搜索树的节点

[英]How to find a Node of a Binary Search Tree without using a recursive method

如果我有一个仅将值作为参数(不是节点)的方法,称为public Node finder (E val) ,无论树的高度和宽度如何,我如何才能找到相应的节点。 如果该方法将 Node 作为参数,那么使用递归将是一个简单的解决方案。 但不幸的是,我不允许更改方法签名。 我怎样才能以聪明的方式而不是我在下面尝试的愚蠢方式来做到这一点,这最终会导致大量的嵌入式if函数

public class BinarySearchTree<E extends Comparable<E>> {
    class Node {
        E value;
        Node leftChild = null;
        Node rightChild = null;
        Node(E value) {
            this.value = value;
        }
    }

    public Node finder(E val) {
        
        if (val == null) return null;
        if (root == null) return null;
        
        boolean flag = false;  
        Node temp = root;
        
        //find if Root Node matches value
        if(temp.value.compareTo(val) == 0) {
            flag = true;
            return temp;
        } 
        //if value is less than root check the left branch
        else if (temp.value.compareTo(val) > 0) {
            
            if(temp.leftChild.value.compareTo(val) == 0) {
                flag = true;
                return temp.leftChild;
            } 
            //more if statements here
        } 
        //if value is more than root check the right branch 
        else {
            if(temp.rightChild.value.compareTo(val) == 0) {
                flag = true;
                return temp.rightChild;
            }
            
            //more if statements here
        }
        
        return null;
    }
}

二叉搜索树有这个有趣的特性:

  • 节点的左子树仅包含值小于节点值的节点。
  • 节点的右子树只包含值大于节点键的节点。

假设您的 class BinarySearchTree持有对根的引用,您可以迭代地遍历二叉树,直到您到达该值或到达叶节点,这意味着您的值在您的二叉搜索树中不存在。 此搜索操作的时间复杂度为 O(log(n))。

这是一些伪代码

Find-Node(val):

    node = root
    while node != null:
      if val == node.val then return root
      if val < node.val then node = node.left
      if val > node.val then node = node.right

    return null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM