1. 程式人生 > >145. Binary Tree Postorder Traversal - Hard

145. Binary Tree Postorder Traversal - Hard

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?

 

 

M1: recursive

time: O(n), space: O(h)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postorder(root, res);
        
return res; } private void postorder(TreeNode root, List<Integer> res) { if(root == null) { return; } postorder(root.left, res); postorder(root.right, res); res.add(root.val); } }

 

M2: iterative

Let's start from the root and then at each iteration pop the current node out of the stack and push its child nodes. In the implemented strategy we push nodes into stack following the order Top->Bottom

 and Left->Right. Since DFS postorder transversal is Bottom->Top and Left->Right the output list should be reverted after the end of loop.

和preorder traversal的iterative解法相似。preorder traversal的iterative解法先從stack中彈出當前node並加入res中,如果當前node有右子節點,右子節點入棧,如果有左子節點,左子節點入棧(stack後進先出)

但由於preorder traversal初始時也是把root入棧,先彈出就必須加在res的末尾,所以要用res.add(0, node.val),所以新增node子節點的順序有調整:如果當前node有左子節點,左子節點入棧;如果當前node有右子節點,右子節點入棧。彈出的時候先彈出右子節點,加在root的左邊,再彈出左子節點,加在right的左邊

time: O(n), space: O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> s = new LinkedList<>();
        if(root == null) {
            return res;
        }
        
        s.offerFirst(root);
        while(!s.isEmpty()) {
            TreeNode cur = s.pollFirst();
            res.add(0, cur.val);
            if(cur.left != null) {
                s.offerFirst(cur.left);
            }
            if(cur.right != null) {
                s.offerFirst(cur.right);
            }
        }
        return res;
    }
}