Binary Tree Postorder Tranversal

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 you do it iteratively?

Solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> st = new Stack<>();
        while(root!=null || !st.isEmpty()){
            while(root!=null){
                ans.add(0,root.val);
                st.add(root);
                root = root.right;
            }
            root = st.pop().left;
        }
        return ans;
    }
}
comments powered by Disqus