【问题标题】:How to find a Node of a Binary Search Tree without using a recursive method如何在不使用递归方法的情况下找到二叉搜索树的节点
【发布时间】:2020-06-20 21:20:16
【问题描述】:

如果我有一个方法只将值作为参数(不是节点),称为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;
    }
}

【问题讨论】:

  • 您始终可以将递归函数转换为迭代函数,其中包含显式 Stack&lt;Node&gt; 并在其中推送“待访问节点”
  • @roookeee 谢谢你的建议!您介意发布一个简短的代码示例,说明您将如何实施此解决方案吗?

标签: java tree binary-tree nodes


【解决方案1】:

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

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

假设您的类 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

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多