This algorithm is only used once in the stack once the stack can be,
//first of all the nodes of the left node of the root node into the stack, until the leaf node, the most left leaf node into the stack, and then determine whether it has reached the leaf node, if it is the value of the node in the stack, then the node out of the stack, because he did not change the PublicArraylist<integer>postordertraversal (TreeNode root) {//Write your code herestack<treenode> s =NewStack<treenode>(); ArrayList<Integer> Result =NewArraylist<integer>(); if(Root = =NULL)returnResult; TreeNode cur; TreeNode Pre=NULL; S.push (root); //for all nodes first into the stack while(!S.empty ()) {cur= S.peek ();//the current operand is the top element of the stack if((cur.left==NULL&&cur.right==NULL)|| (Pre! =NULL&& (pre==cur.left| | pre==cur.right))) { //if the current operand is empty, or p has left child or right child, but the left child and right child have been visited, indicating that the node can be accessed, then this node is useless and can be out of the stackResult.add (Cur.val); S.pop (); Pre= cur;//keep the current node for a while, and leave it to determine whether to access his parent node. }Else { if(cur.right!=NULL) S.push (cur.right);//If the right node of the current node is not empty on the stack, only the right node into the stack before you can guarantee that the order of access is right, if(cur.left!=NULL) S.push (Cur.left);//If left child is not empty, left child last into the stack } } returnResult; }
Novice Learning Algorithm----binary tree (sequential traversal)