145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

Language:Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List postorderTraversal(TreeNode root) {
        LinkedList resList = new LinkedList<>();
        Stack stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                resList.addFirst(cur.val);
                cur = cur.right;
            } else {
                TreeNode node = stack.pop();
                cur = node.left;
            }
        }
        return resList;
    }
}

Analysis:

  1. iterative

Submission Detail

Accepted Solutions Runtime Distribution

Accepted Solutions Memory Distribution

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