Given a binary tree, return the postorder traversal of its nodes’ values.
Example :
Given binary tree
1
\
2
/
3
return [3,2,1].
Using recursion is not allowed.
Method:
pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root.
Solution:
Time: O(n) Space: O(n)
/** * Definition for binary tree * class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { * val = x; * left=null; * right=null; * } * } */ public class Solution { public ArrayList<Integer> postorderTraversal(TreeNode A) { ArrayList<Integer> result = new ArrayList<>(); if (A == null) return result; Deque<TreeNode> stack = new ArrayDeque<>(); stack.push(A); while (!stack.isEmpty()) { TreeNode curr = stack.pop(); result.add(curr.val); if (curr.left != null) { stack.push(curr.left); } if (curr.right != null) { stack.push(curr.right); } } Collections.reverse(result); return result; } }