Question

I'm trying to write a pseudocode for a recursive function that should process a binary tree. But the problem is that the function should return two variables. I know that functions are supposed to return on variable, and for more return values they should use list, array or vector, but I don't know how to present it as a pseudocode.

Does it look correct for a pseudocode?

function get_min(node *p)
begin
     if (p==NULL) then        
          return list(0,0);
     else 
          (vl,wl) = get_min(p->left)
          (vr,wr) = get_min(p->right)
          if (vl > vr) then
              return list(vr + p->cost, 1)
          else
              return list(vl + p->cost, 0)
          end if
     end if
end function
Was it helpful?

Solution

Since it's pseudo-code, just about anything goes.

However, I'd rather go for omitting "list":

return (0, 0)
return (vr + p->cost, 1)
return (vl + p->cost, 0)

There doesn't seem to be any real benefit to putting "list" there - the (..., ...) format pretty clearly indicates returning two values already - there's no need to explicitly say you're returning them in a list.

Side note: You mention list, array or vector, but pair is another option in some languages, or wrapping the two in an object (typically giving the advantage of compile-time type checking - not really applicable in pseudo-code, obviously).

You could consider replacing "list" with "pair" instead of removing it if you wish to make it clear that the function only ever returns exactly 2 values.

OTHER TIPS

If you pass parameters as reference , then there is no need to use lists as @Dukeling suggested .

void function get_min(node *p , int *cost , int * a)
begin
     if (p==NULL) then        
          *cost =0 ; *a =0 ; return ;
     else 
           get_min(p->left ,vl ,vw)
           get_min(p->right , vr , wr)
          if (vl > vr) then
              *cost = vl + p->cost , *a =0 ; return;  
              else
              *cost = vl + p->cost , *a =0 ; return ;
          end if
     end if
end function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top