c - Is there any faster implementation for this Splay Tree range sum? -


i have coded splay tree. nodes represented this.

struct node{     node *l;  /// left  node     node *r;  /// right node     int v;    /// value }; 

now, need know summation of numbers in tree within range. this, implemented following function named 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 global int variable initialized 0 before calling summation function. 2 parameters st & ed defines range (inclusive).

the summation function works @ complexity of o(n). can suggest faster implementation this??

this splay tree implementation did time ago , tested against spoj evaluation system (written in c++) :

https://ideone.com/aqgepf

this tree implementation supports u asking (range sum in o(log(n)).

the key idea here use split , merge, extract subtree covering range. additionally each node contains field sum, sum of keys in subtree. sum field lazily evaluated , relayed during split operation (along splitting line), allows not go deeper levels not required calculated.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -