I found this problem and I am not very sure if my approach approach is right:
"A binary tree can be encoded using two functions l and r such that for a node n, l(n) gives the left child of n(or nil if there is none) and r(n) gives the right child(or nil if there is none).Let Test(l,r,x) be a simple recursive algorithm for taking a binary tree encoded by the l and r functions together with the root node x for the binary tree, and returns "yes" if no node in the tree has exactly one child. Give the pseudocode for this algorithm."
I tried this:
test(l,r,x)
if((l(x)!=null && r(x)!=null) || (l(x)==null && r(x)==null))
return "yes"
else return "no"
if(test(l,r,l(x))=="yes") test (l,r,l(x)) else return "no"
if(test(l,r,r(x))=="yes") test (l,r,r(x)) else return "no"
return "yes"
Is it correct? If l and r are functions, why are they passed as normal parameters when the function is called?
Thank you in advance for your answers!
the first thing you do is either return yes or no, so the last part is unreachable.
I would change it so that if you have one child, you return no, otherwise you return yes or no depending on if your children meet the criteria.
test(l,r,x)
if((l(x)!=null && r(x)==null) || (l(x)==null && r(x)!=null))
return "no"
if(l(x) == null && r(x) == null)
return "yes"
return test(l,r,l(x)) && test(l,r,r(x))