Question
Given a binary tree, return the postorder traversal of its nodes 'values.
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
Return[3,2,1].
Note: Recursive solution is trivial, cocould you do it iteratively?
Method
/*** Ensure that the root node can be accessed only after the access from the left and right children. Therefore, for any node P, first import it into the stack. * If P does not have a left or right child, you can directly access it. Or P has a left or right child, but both the left and right children have been accessed, you can also directly access this node. * If the preceding two conditions are not met, P's right child and left child are added to the stack in sequence. * This ensures that each time the top element of the stack is taken, the left child is accessed in front of the right child, and the left child and the Right child are accessed in front of the root node. */Private Stack
Stack = new Stack
(); Public ArrayList
PostorderTraversal (TreeNode root) {ArrayList
Al = new ArrayList
(); If (root! = Null) {TreeNode cur = null; TreeNode pre = null; stack. push (root); while (stack. size ()! = 0) {cur = stack. peek (); if (cur. left = null & cur. right = null) | (pre! = Null & (pre = cur. left | pre = cur. right) {al. add (cur. val); pre = cur; stack. pop ();} else {if (cur. right! = Null) {stack. push (cur. right);} if (cur. left! = Null) {stack. push (cur. left) ;}}} return al ;}