I have a binary tree that is accessed as a cell array in MATLAB (e.g. a{1}{2}
). I was able to write a recursive function (below) that is able to access all the fringe nodes of the tree. My next task is to replace the values at the fringe nodes with other values. However, I am having difficulties with this part. With every call of the recursive function, the values do not keep their new values, rather they revert to their original ones. Is there a simple way to ensure that the values remain updated in the function? Thank you!
Here is the code:
function findLeaves(a)
if(iscellstr(a) == 1) % just above fringe node
a{2} = 2; %change fringe node to value 2
else
if(length(a) == 3 || length(a) == 2) % go left
findLeaves(a{2});
end
if (length(a) == 3) % go right
findLeaves(a{3});
end
end
end
In matlab, the standard calls for built-in data types are by value, which means that the parameters passed are protected against changes made in the function. The exceptions are graphic handles, java handles and classes that inherit from handle classes type.
So, you must pass as output the results from the changes in order to you keep the calculated values.
function a = findLeaves(a)
if(iscellstr(a) == 1) % just above fringe node
a{2} = 2; %change fringe node to value 2
else
if(length(a) == 3 || length(a) == 2) % go left
a{2}=findLeaves(a{2});
end
if (length(a) == 3) % go right
a{3}=findLeaves(a{3});
end
end