It seems obvious that a recursion is realized using stacks. But how indeed a general recursion realized using a stack? For example, if we have a custom function that is recursive, can we rewrite the code using just a stack and iteration?
Here is one example (I was giving the wrong example in another post):
def recursiveCall(node):
if node==None:
return (0,True)
(left,lstatus) = recursiveCall(node.left)
(right,rstatus) = recursiveCall(node.right)
if lstatus==True and rstatus==True:
if abs(left-right)<=1:
return (max(left,right)+1,True)
else:
return (0,False)
else:
return (0,False)
or an easier one :
def recursiveInorder(node):
if node==None:
return
recursiveInorder(node.left)
print(node.val)
recursiveInorder(node.right)
how do you realize this recursion using stacks? Note, I am not asking for an iteration solution to the above two examples. I believe there must be. But I suppose those iteration solutions are not trying to reproduce the recursion mechanism using a stack. What I wanted is to see, if ever possible, those recursions can be completely replaced by custom coded stack-mechanism (basically making the implicit recursion mechanism embedded in the compiler or whatsoever explicit) .
I think one needs to find a way to track and restore program status, local variables etc? thx.
node class is defined as:
class node:
def __init__(self,x):
self.val=x
self.left=None
self.right=None