algorithm - postorder using tail recursion -
I'm getting this link, which suggests a way to reproduce the tail of the poster. However, it uses 2 stacks, it's just a way to do this with a stack. Thanks!
The java code pasted from the link below:
public static final & lt; T & gt; Zero Post Order (tree & lt; T & gt; Root) {stack & lt; Tree & lt; T & gt; & Gt; Stack = new stack & lt; Tree & lt; T & gt; & Gt; (); Stack & LT; Tree & lt; T & gt; & Gt; Traveler = New Stack & lt; Tree & lt; T & gt; & Gt; (); Stack.push (root); While (! Stack.isEmpty ()) {tree & lt; T & gt; Node = stack.pop (); If (node. Right! = Null) stack.push (node right); } If (node. Left! = Null) {stack.push (node. Left); } Traveler Peach (node); } While (! Traveler.ISEacti) {System.out.println (Traversal Pop (.) Value.toString ()); }}
Yes, but the code needs to be structured differently, a recursive algorithm A proper stack-based simulation of Keep should be a node on the stack until the node and its children are completely crossed. The stack should contain examples of a class that contains information about how many children have been traversed: say: public class StackElement & lt; T & gt; {Public tree & lt; T & gt; Node; Public Intu neumatroves children; } (Use public areas for simplicity) Whenever you press a node on the stack, push a StackElement to the node And where numTraversedChildren is 0. In the top of the loop, peek (do not pop) a pile to find the top element. If and only if numtraversedChildren == 2 , you know that all the children in this node have been exceeded. In that case, you can process that node (in your case, print it) and then pop it. Otherwise, place the node on the stack, increment numTraversedChildren , or push its left child (if the old value of numTraversedChildren was 0) or its right child (if the old NumTraversedChildren was the value of 1). Note that when this approach is followed, while the push / pop operation on the loop and stack will be effectively effected The simulation function consists of a call: a push is a call, a pop is a refund, and stack all the parameters and the place Financial variable holds for each function call. The element at the top of the stack always represents the function that is currently executed.
Comments
Post a Comment