145. Binary Tree Postorder Traversal

/**
 * 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> results = new ArrayList<Integer>();
        if(root == null)
            return results;
        
        Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
        TreeNode walker = root;
        TreeNode lastProcessed = null;
        while(walker!=null || !stack.isEmpty())
        {
            if(walker == null)
            {
                TreeNode processing = stack.peek();
                if(processing.right != null && processing.right != lastProcessed)
                {
                    walker = processing.right;
                }
                else
                {
                    results.add(processing.val);
                    lastProcessed = stack.pop();
                }
            }
            else
            {
                stack.push(walker);
                walker = walker.left;
            }
            
        }
        return results;
    }
}

 

你可能感兴趣的:(145. Binary Tree Postorder Traversal)