Tag:io ar os java on Data ef amp as
Package Tree.binarytree;import java.util.stack;/** * Recursive and non-recursive implementation of sequential traversal of binary tree * * @author WL * */public class Bitreepostorder {/ /post-traversal recursive implementation public static void Bitreepostorderbyrecursion (Bitreenode root) {if (root = null) {return;} Bitreepostorderbyrecursion (Root.leftnode); bitreepostorderbyrecursion (Root.rightnode); System.out.println (root.data);} /** * post-order traversal of non-recursive implementation to ensure that the root node in the left child and right child access before access, so for any node current, first put it into the stack, if current does not exist left child * and right child, you can access it directly, or current existing left child or right child, But the left child and the right child have been visited, and can also access the change node directly. In either case, the current right child and left child (note that the right child is first left child) are placed in the stack. This ensures that each time the top element of the stack is taken, the left child is accessed before the right child, and the left child and right child are accessed in front of the root node * * @param root */public static void Bitreepostorder (Bitreenode root) { stack<bitreenode> stack = new stack<bitreenode> ();//stack, for storing two fork tree nodes bitreenode current = root;// The current node Bitreenode pre = null;//the last visited node Stack.push (root), while (!stack.empty ()) {present = Stack.peek (); if ( Current.leftnode = = NULL && Current.rightnode = = null) | | (pre = null && (pre = = Current.leftnode | | pre = current.Rightnode)) {System.out.println (current.data); Stack.pop ();p re = current;} else {if (Current.rightnode! = null) { Stack.push (Current.rightnode);} if (Current.leftnode! = null) {Stack.push (Current.leftnode);}}}}
Java Data Structure Series--Tree (5): Recursive and non-recursive implementation of post-sequence traversal of two-tree