我编写了一个展开树。节点是这样表示的。
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
被初始化。&两个参数定义范围(包括)。0
summation
st
ed
该summation
函数的工作复杂度为 O(n)。任何人都可以为此建议更快的实施吗?