My Java 2 stack solution to post order traversal


  • 0
    Z

    It is pretty straightforward since using traditional DFS renders a reversed list compared to the answer. If you just use DFS by push left node, then right node, you will just get a reverse of postorder.

    My code goes like:
    
    public class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if (root == null) return list;
            Stack<TreeNode> stack1 = new Stack<TreeNode>();
            Stack<TreeNode> stack2 = new Stack<TreeNode>();
            
            // DFS init
            stack1.push(root);
            while (!stack1.isEmpty()) {
                TreeNode cur = stack1.pop();
                stack2.push(cur);
                if (cur.left != null) {
                    stack1.push(cur.left);
                }
                if (cur.right != null) {
                    stack1.push(cur.right);
                }
            }
            
            while (!stack2.isEmpty()) {
                list.add(stack2.pop().val);
            }
            return list;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.