KatInterview

145. Binary Tree Postorder Traversal

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a postorder traversal of a binary tree. Postorder traversal visits nodes in the order: Left Subtree -> Right Subtree -> Root. The problem also includes a follow-up requesting an iterative solution, as the recursive approach is straightforward but often less efficient in terms of memory due to call stack overhead.

Solution

Binary Tree Postorder Traversal in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from typing import List, Optional

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []

        stack = [root]
        result = []
        
        while stack:
            node = stack.pop()
            # Add current node's value to the result list
            result.append(node.val)
            
            # Push left child first, then right child.
            # This ensures that when we pop, we get the right child before the left child,
            # achieving a Root-Right-Left traversal order.
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
                
        # The result is currently in Root-Right-Left order.
        # Reverse it to get the postorder traversal (Left-Right-Root).
        return result[::-1]

Binary Tree Postorder Traversal in Java

/**
 * 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;
 *     }
 * }
 */
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Collections;

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            // Add current node's value to the result list
            result.add(node.val);

            // Push left child first, then right child.
            // This ensures that when we pop, we get the right child before the left child,
            // achieving a Root-Right-Left traversal order.
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }

        // The result is currently in Root-Right-Left order.
        // Reverse it to get the postorder traversal (Left-Right-Root).
        Collections.reverse(result);
        return result;
    }
}

Binary Tree Postorder Traversal in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <vector>
#include <stack>
#include <algorithm>

class Solution {
public:
    std::vector<int> postorderTraversal(TreeNode* root) {
        std::vector<int> result;
        if (root == nullptr) {
            return result;
        }

        std::stack<TreeNode*> s;
        s.push(root);

        while (!s.empty()) {
            TreeNode* node = s.top();
            s.pop();
            // Add current node's value to the result list
            result.push_back(node->val);

            // Push left child first, then right child.
            // This ensures that when we pop, we get the right child before the left child,
            // achieving a Root-Right-Left traversal order.
            if (node->left) {
                s.push(node->left);
            }
            if (node->right) {
                s.push(node->right);
            }
        }

        // The result is currently in Root-Right-Left order.
        // Reverse it to get the postorder traversal (Left-Right-Root).
        std::reverse(result.begin(), result.end());
        return result;
    }
};

Binary Tree Postorder Traversal in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function postorderTraversal(root: TreeNode | null): number[] {
    if (!root) {
        return [];
    }

    const stack: TreeNode[] = [root];
    const result: number[] = [];

    while (stack.length > 0) {
        // The non-null assertion `!` is safe here because we check stack.length > 0
        const node = stack.pop()!;
        // Add current node's value to the result list
        result.push(node.val);

        // Push left child first, then right child.
        // This ensures that when we pop, we get the right child before the left child,
        // achieving a Root-Right-Left traversal order.
        if (node.left) {
            stack.push(node.left);
        }
        if (node.right) {
            stack.push(node.right);
        }
    }

    // The result is currently in Root-Right-Left order.
    // Reverse it to get the postorder traversal (Left-Right-Root).
    return result.reverse();
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.