Java Data Structure series-tree (5): recursive and non-recursive implementations of post-sequential traversal of Binary Trees
Package tree. binarytree; import java. util. stack; /*** recursive and non-Recursive Implementation of Binary Tree post-sequential traversal ** @ author wl **/public class BitreePostOrder {// Recursive Implementation of post-sequential traversal public static void biTreePostOrderByRecursion (BiTreeNode root) {if (root = null) {return;} biTreePostOrderByRecursion (root. leftNode); biTreePostOrderByRecursion (root. rightNode); System. out. println (root. data);}/*** the non-Recursive Implementation of post-sequential traversal must ensure that the root node can be accessed only after access by the left and right children. Therefore, for any node current, first, import it into the stack, If current does not have a left child * or a right child, you can directly access it. Or current has a left or right child, but both the left and right children have nearly accessed it, you can also directly access the * Change node. If the preceding two conditions are not met, the right and left children of current are added to the stack. This ensures that the left child is accessed before the right child each time the top element of * stack is obtained, both the left and right children are accessed in front of the root node ** @ param root */public static void biTreePostOrder (BiTreeNode root) {Stack
Stack = new Stack
(); // Stack, used to store the Binary Tree node BiTreeNode current = root; // the current node BiTreeNode pre = null; // The previous accessed node stack. push (root); while (! Stack. empty () {current = stack. peek (); if (current. leftNode = null & current. rightNode = null) | (pre! = Null & (pre = current. leftNode | pre = current. rightNode) {System. out. println (current. data); stack. pop (); pre = current;} else {if (current. rightNode! = Null) {stack. push (current. rightNode);} if (current. leftNode! = Null) {stack. push (current. leftNode );}}}}}