pseudocode - return sum of all non-leaf nodes, binary tree -
a binary tree can encoded using 3 functions: l, r , k such node n, l (n) gives left child of n (or nil if there none), r(n) gives right child of n (or nil if there none), , k(n) gives key value @ n.
let treesum(l, r, x, k) simple recursive algorithm takes binary tree encoded l, r, , k functions, root x, , returns sum of key values @ non-leaf nodes. give pseudocode algorithm.
however think this?
treesum(l,r,x,k) if(l(n) number) x = k(l(n)) + x return treesum(l,r,x,k) else if ( node leaf or not number) return nil if(r(n) number) x = k(r(n)) + x return treesum(l,r,x,k) else if ( node leaf or not number) return nil not quite sure how go question. need find way non-leaf nodes , add values of nodes up.
this might work...
treesum(l,r,x,k)
if x == nil k[x] = 0 else sum = k[x] + treesum(l,r,l[x],k) + treesum(l,r,r[x],k) return sum
Comments
Post a Comment