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].
2. Implementation
classSolution {publicList<Integer> postorderTraversal(TreeNode root) {List<Integer> res =newArrayList<>();if (root ==null) {return res; }Stack<TreeNode> stack =newStack<>();stack.push(root);TreeNode curNode =null, preNode =null;while (!stack.isEmpty()) { curNode =stack.peek();// Case 1: Traverse down the tree, put left child into stack if it exists, otherwise put right childif (preNode ==null||preNode.left== curNode ||preNode.right== curNode) {if (curNode.left!=null) {stack.push(curNode.left); }elseif (curNode.right!=null) {stack.push(curNode.right); } }// Case 2: Travese up from left childelseif (curNode.left== preNode) {if (curNode.right!=null) {stack.push(curNode.right); } }// Case 3: Traverse up from right childelse {res.add(curNode.val);stack.pop(); } preNode = curNode; }return res; }}