KatInterview

144. Binary Tree Preorder 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 us to perform a preorder traversal on a given binary tree and return the values of the nodes in that order. Preorder traversal follows a specific sequence: Root -> Left -> Right. This means we first visit the current node, then we traverse its entire left subtree, and finally, we traverse its entire right subtree.

Solution

Binary Tree Preorder 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
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        # Handle the edge case of an empty tree
        if not root:
            return []
        
        result = []
        # Use a list as a stack
        stack = [root]
        
        while stack:
            # Pop the last element from the stack
            node = stack.pop()
            # Visit the node
            result.append(node.val)
            
            # Push the right child first, then the left child.
            # Because a stack is LIFO (Last-In, First-Out), the left child
            # will be processed before the right child.
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
                
        return result

Binary Tree Preorder 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;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        // Use Deque as a more modern and efficient stack implementation
        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            // Visit the node
            result.add(node.val);
            
            // Push right child first, then left child, to ensure left is processed first (LIFO)
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        
        return result;
    }
}

Binary Tree Preorder 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) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        if (root == nullptr) {
            return result;
        }

        stack<TreeNode*> nodeStack;
        nodeStack.push(root);

        while (!nodeStack.empty()) {
            TreeNode* node = nodeStack.top();
            nodeStack.pop();
            
            // Visit the node
            result.push_back(node->val);

            // Push right child first so that left child is processed first (LIFO)
            if (node->right) {
                nodeStack.push(node->right);
            }
            if (node->left) {
                nodeStack.push(node->left);
            }
        }

        return result;
    }
};

Binary Tree Preorder 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 preorderTraversal(root: TreeNode | null): number[] {
    // Handle the edge case of an empty tree
    if (!root) {
        return [];
    }

    const result: number[] = [];
    // Use an array as a stack
    const stack: TreeNode[] = [root];

    while (stack.length > 0) {
        // Pop the last element from the stack. The non-null assertion `!` is safe
        // because we only push non-null nodes and check stack.length > 0.
        const node = stack.pop()!;
        
        // Visit the node
        result.push(node.val);

        // Push the right child first, then the left child.
        // Because a stack is LIFO (Last-In, First-Out), the left child
        // will be processed before the right child.
        if (node.right) {
            stack.push(node.right);
        }
        if (node.left) {
            stack.push(node.left);
        }
    }

    return result;
};

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.