【发布时间】:2016-08-08 08:24:41
【问题描述】:
我编写了一个展开树。节点是这样表示的。
struct Node{
Node *l; /// The left Node
Node *r; /// The right Node
int v; /// The Value
};
现在,我需要知道特定范围内树中所有数字的总和。为此,我实现了以下名为summation.的函数
void summation(Node *R, int st, int ed)
{
if(!R) return;
if(R->v < st){ /// should not call left side
summation(R->r, st, ed);
}
else if(R->v > ed){ /// should not call right side
summation(R->l, st, ed);
}
else{ /// should call both side
ret+=R->v;
summation(R->l, st, ed);
summation(R->r, st, ed);
}
return;
}
ret 是一个全局的int 变量,在调用summation 函数之前初始化为0。 st & ed 这两个参数定义了范围(包括)。
summation 函数的工作复杂度为 O(n)。任何人都可以为此建议更快的实现吗?
【问题讨论】:
-
void summation(Node *R, ...)Node 不是类型名称。你在用 C++ 吗? -
Node 是我在问题前面提到的结构。
-
既然你不知道你一定是在使用 C++。 (在 C 中,
struct Node {...};确实 not 暗示typedef struct Node{...};)
标签: c algorithm data-structures binary-search-tree splay-tree