Binary Tree Postorder Traversal

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

 

Example 1:

Input: root = [1,null,2,3]

Output: [3,2,1]

Explanation:



Example 2:

Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]

Output: [4,6,7,5,2,9,8,3,1]

Explanation:



Example 3:

Input: root = []

Output: []

Example 4:

Input: root = [1]

Output: [1]


Constraints:

  • The number of the nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100



My Solution

To do the postorder traversal, we first recursively visit the left subtree, then we recursively visit the right subtree, and then finally we add the current node’s value to the output list.

Time complexity would be O(n), where n is the number of nodes in the tree. Space complexity would be O(1) because we only require constant extra space.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> out = new ArrayList<>();

        postorder(root, out);

        return out;
    }

    public void postorder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }

        postorder(root.left, list);
        postorder(root.right, list);
        list.add(root.val);
    }
}
Previous
Previous

Intersection of Two Linked Lists

Next
Next

Binary Tree Preorder Traversal