Home › Forums › kdb+ › How to walkthrough a tree and calculate value on path? › Re: How to walkthrough a tree and calculate value on path?
-
It’s faster to keep track of the running products at each step:
tree:([]parent:`A`A`A`B`B`E`E;child:`B`C`D`E`F`G`H;data:1 2 3 4 5 6 7); sort:{x iasc 2#/:x:x@'(-1+count each x),:1 0} step:{.[z;(::;0);*;]y -2#/:z:(z,'x l)where(l:last each z)in key x} walk2:{ d:exec child!parent from x; w:exec(child,'parent)!data from x; sort raze 1_(step[d;w;])1,'(except/)x`child`parent } walk2 tree `A `C 2 `A `D 3 `A `F 5 `A `G 24 `A `H 28 `B `F 5 `B `G 24 `B `H 28 `E `G 6 `E `H 7 q)\ts do[50000;walk tree] 1930 3584j q)\ts do[50000;walk2 tree] 1259 3440j