二叉搜索树在大树上的性能失败

时间:2018-03-28 09:58:24

标签: java

我一直在寻找类似的情况,但我似乎无法找到一个。

以下是我需要做的事情:

  

编写一个函数,检查给定的二叉搜索树是否包含给定值。

     

例如,对于以下树:

     
      
  • n1(值:1,左:null,右:null)
  •   
  • n2(值:2,左:n1,右:n3)
  •   
  • n3(值:3,左:null,右:null)
  •   
     

对contains(n2,3)的调用应返回true,因为在n2处具有root的树包含数字3。

这是我的代码:

class Node {
 public int value;
 public Node left, right;

 public Node(int value, Node left, Node right) {
    this.value = value;
    this.left = left;
    this.right = right;
 }
}

public class BinarySearchTree {
 public static boolean contains(Node root, int value) {
    if(value == root.value)
        return true;

    if(root.left != null && contains(root.left, value))
        return true;

    if(root.right != null && contains(root.right, value))
        return true;

    return false;
 }

 public static void main(String[] args) {
    Node n1 = new Node(1, null, null);
    Node n3 = new Node(3, null, null);
    Node n2 = new Node(2, n1, n3);

    System.out.println(contains(n2, 3));
 }
}

然而,它在最后一次测试中仍然失败:

  

对大树进行性能测试:超出时间限制

如果有人知道如何优化我的流程,那将是一个很大的帮助。我实际上已经没想到了:(

3 个答案:

答案 0 :(得分:0)

问题是您不将此树用作二进制搜索树。你检查左右分支。

二叉搜索树"additionally satisfies the binary search property, which states that the key in each node must be greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the right sub-tree."

这意味着您只需要检查其中一个分支。

如果您同时检查两者,那么特殊构造的测试用例可以使您的搜索花费很长时间。你基本上会遍历整棵树。

答案 1 :(得分:0)

使用二叉搜索树的性能提升来自于将值除以更大或更小。因此,您需要检查该值是否小于节点中当前的值,如果是,则查看树的左侧部分,否则在您找到搜索到的值之前,您将看起来正确。

看看一个包含许多元素的数组(让我们说100)。当您搜索第70个值时,您必须进行70次检查if(foundValue == searchedValue)

现在对树采取相同的做法。您的起始节点保持值50,75更大,因此您可以查看树中的子集51-100。这里遇到的第一个节点是75,所以你看一下子集51-74,依此类推。

答案 2 :(得分:0)

我想赞扬lexicoreivo-vidovic给我一个关于二元搜索树的更实用的解释。如果我有足够的声誉,我会赞成你的帖子。非常感谢你。

在旁注中,这是我所做的与性能测试问题相反的问题:

    if(value <= root.value) {
        if (root.left != null && contains(root.left, value))
            return true;
    } else if (value >= root.value) {
        if (root.right != null && contains(root.right, value))
            return true;
    }