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, could do it iteratively?
Solution:
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicList<integer>postordertraversal (TreeNode root) { Alist<integer> res =NewArraylist<integer>(); - if(root==NULL)returnRes; - theStack<treenode> Nstack =NewStack<treenode>(); -Stack<integer> record =NewStack<integer>(); - Nstack.push (root); -Record.push (0); + - while(Nstack.size ()!=0){ +TreeNode cur =Nstack.peek (); A if(cur.left==NULL&& cur.right==NULL){ at Res.add (cur.val); - Nstack.pop (); - Record.pop (); - Continue; - } - in intval =Record.peek (); - if(val==0){ to Record.pop (); +Record.push (val+1); - if(cur.left!=NULL){ the Nstack.push (cur.left); *Record.push (0); $ }Panax Notoginseng Continue; - } the + if(val==1){ A Record.pop (); theRecord.push (val+1); + if(cur.right!=NULL){ - Nstack.push (cur.right); $Record.push (0); $ } - Continue; - } the - if(val==2){Wuyi Res.add (cur.val); the Nstack.pop (); - Record.pop (); Wu Continue; - } About } $ - returnRes; - - } A}
Leetcode-binary Tree postorder Traversal