简体   繁体   English

二分搜索树中Java方法的成本

[英]Cost of a Java method in a binary-search-tree

We have the Java method rangeQuery_count(BSTNode,int,int) . 我们有Java方法rangeQuery_count(BSTNode,int,int) Given the root of a BST (keys int) and an interval [a,b], this method returns number of keys of the BST belong to the interval. 给定BST的根(键int)和间隔[a,b],此方法返回属于该间隔的BST的键数。

static int rangeQuery_count(BSTNode v, int a, int b) { //a<=b
   if(v==null) return 0;
   if(v.key < a) return rangeQuery_count(v.right, a, b);
   else if(v.key > b) return rangeQuery_count(v.left, a, b);
   else return 1 + rangeQuery_count(v.right, a, b) + rangeQuery_count(v.left, a, b);
}

I have to determine an asymptotic estimate of the cost of the algorithm in function of the number of nodes n of the BST. 我必须根据BST的节点数n确定算法成本的渐近估计。 I'm just starting to study these topics and I would like to understand how to calculate the cost of a program. 我刚刚开始研究这些主题,我想了解如何计算程序成本。

The first thing to recognise is that the cost depends on the particular values of the input parameters, in your case it depends, for instance, on how many nodes in the search tree fall within the interval. 首先要认识到的是,成本取决于输入参数的特定值,例如,取决于例如搜索树中有多少个节点落在该间隔内。 The usual simplifying assumption made here is to calculate the worst possible case. 此处所做的通常简化假设是计算最坏的情况。 In this case, that will be when all of the nodes in the tree lie within the interval. 在这种情况下,就是树中的所有节点都位于间隔内。 In that case you will always take the final clause of the else as long as v is not null, you will visit each node of the tree once, and if there n nodes in the tree the cost will go up roughly linearly with n. 在这种情况下,只要v不为null,您将始终使用else的最后一个子句,您将访问树的每个节点一次,并且如果树中有n个节点,则开销将与n大致成线性增长。

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

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