Give a function to calculate the depth of the tree:
function treedepth (curtree) { ifnull) return 0; Else { var leftdepth = treedepth (curtree.left); var rightdepth = treedepth (curtree.right); return 1 + Math.max (leftdepth, rightdepth);} }
Now you need to rewrite this function in CPS style.
Avoid the return value of the function, but instead pass the return value to continuation. Remember, continuation is what you need to do when the function is finished. So write the following code
function treedepth (Curtree, afterdepth) { ifnull) afterdepth (0); Else { // Undone:var leftdepth = treedepth (curtree.left); // Undone:var rightdepth = treedepth (curtree.right); Afterdepth (1 + Math.max (leftdepth, rightdepth));} }
This assumes that addition and maximum values are not written in CPS style to reduce the difficulty.
Now you need to combine recursive calls. Consider the second recursive call, well, what is its continuation? So what do you need to do when the depth of the right subtree is determined? Two things, first, the maximum value of the depth of the left and right subtree needs to be calculated and then added 1; second, it needs to be guaranteed that it will call continuation when done. So, write a closure to do both of these things.
function Treedepth (Curtree, afterdepth) { if (curtree = null ) afterdepth ( 0 else { function Afterright (rightdepth) {afterdepth ( 1+math.max (Leftdepth, rightdepth)); // Undone:var leftdepth = Treedepth (cu Rtree.left); Treedepth (Curtree.right, afterright); }}
Hmm, there's been progress. So what do I need to do when the depth of Zuozi is determined? The left depth is passed to continuation, which continuation on the right tree to determine the depth of the right tree, then determine the maximum value, and then call afterdepth this continuation.
function Treedepth (Curtree, afterdepth) { if (curtree = null ) afterdepth ( 0 else { function Afterleft (leftdepth) { function Afterright (rightdepth) {afterdepth ( 1+
math.max (Leftdepth, rightdepth)); } treedepth (Curtree.right, afterright); } treedepth (Curtree.left, afterleft); }}
Original: https://blogs.msdn.microsoft.com/ericlippert/2005/08/11/recursion-part-five-more-on-cps/
Recursive--cps (ii)