Home › Forums › kdb+ › How to walkthrough a tree and calculate value on path? › Re: How to walkthrough a tree and calculate value on path?
-
Another method:
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); dl:-1_ s:{x iasc 2#/:x} // sort lr:{flip dl(x)y} // leaf to root lar:{(sum[n]-2)dlx where n:not null x} // leaf to all roots gw:{((last;first)@:y),prd x dl flip 1 nexty} // get weights walk:{ d:exec child!parent from x; w:exec(child,'parent)!data from x; s gw[w;]each raze lar each lr[d;](except/)x`child`parent } walk 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