0

A binary tree can be encoded using three functions: l, r and k such that for a node n, l (n) gives the left child of n (or nil if there is none), r(n) gives the right child of n (or nil if there is none), and k(n) gives the key value at n.

Let TreeSum(l, r, x, k) be simple recursive algorithm that takes a binary tree encoded by the l, r, and k functions, with the root x, and returns the sum of the key values at the non-leaf nodes. Give the pseudocode for this algorithm.

However I think it could be this?

TreeSum(l,r,x,k)
  if(l(n) is a number)
  x = k(l(n)) + x
     return TreeSum(l,r,x,k)
 else if ( node is a leaf or is not a number)
     return nil 

 if(r(n) is a number)
    x = k(r(n)) + x 
       return TreeSum(l,r,x,k)
 else if ( node is a leaf or is not a number)
    return nil

Not quite sure how to go about this question. I need to find a way to get to all the non-leaf nodes and add the values of the nodes up.

Leonid Glanz
  • 1,261
  • 2
  • 16
  • 36
Hyune
  • 11
  • 1
  • 1
  • 6

1 Answers1

0

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