KatInterview

257. Binary Tree Paths

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 requires us to find all paths from the root node to every leaf node in a given binary tree. A path should be represented as a string with node values joined by "->". A leaf node is defined as a node with no children.

Solution

Binary Tree Paths 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        result = []
        # path stores node values for the current path being explored.
        path = []
        
        def dfs(node):
            # Base case: if the node is None, we stop.
            if not node:
                return

            # Add the current node's value to the path.
            path.append(str(node.val))

            # If it's a leaf node, we've found a complete path.
            # Join the path elements and add to the result.
            if not node.left and not node.right:
                result.append("->".join(path))
            else:
                # If not a leaf, continue to children.
                dfs(node.left)
                dfs(node.right)

            # Backtrack: remove the current node from the path when moving up the recursion tree.
            path.pop()

        # Start the DFS from the root node.
        dfs(root)
        return result

Binary Tree Paths 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<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        // Per constraints, root is never null. If it could be, we'd add: if (root == null) return result;
        StringBuilder path = new StringBuilder();
        dfs(root, path, result);
        return result;
    }

    private void dfs(TreeNode node, StringBuilder path, List<String> result) {
        if (node == null) {
            return;
        }

        // Store the length of the path before appending the current node's value.
        // This is used for backtracking.
        int len = path.length();
        
        // If the path is not empty, it means this is not the root node,
        // so we need to add an arrow before the value.
        if (len > 0) {
            path.append("->");
        }
        path.append(node.val);

        // If it's a leaf node, we've found a path. Add it to the results.
        if (node.left == null && node.right == null) {
            result.add(path.toString());
        } else {
            // Otherwise, continue exploring the left and right subtrees.
            dfs(node.left, path, result);
            dfs(node.right, path, result);
        }
        
        // Backtrack: remove the current node and arrow (if any) from the path.
        path.setLength(len);
    }
}

Binary Tree Paths 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<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        // Per constraints, root is never null. If it could be, we'd add: if (!root) return result;
        string path = "";
        dfs(root, path, result);
        return result;
    }

private:
    void dfs(TreeNode* node, string path, vector<string>& result) {
        // Append the current node's value to the path.
        // Passing 'path' by value creates a copy for each recursive branch,
        // implicitly handling backtracking.
        path += to_string(node->val);

        // If it's a leaf node, we have found a complete path.
        if (node->left == nullptr && node->right == nullptr) {
            result.push_back(path);
            return;
        }

        // If not a leaf, continue exploring.
        path += "->";
        if (node->left != nullptr) {
            dfs(node->left, path, result);
        }
        if (node->right != nullptr) {
            dfs(node->right, path, result);
        }
    }
};

Binary Tree Paths 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 binaryTreePaths(root: TreeNode | null): string[] {
    const result: string[] = [];
    // Per constraints, root is never null. If it could be, we'd add: if (!root) return result;
    
    // Path stores node values for the current path being explored.
    const path: number[] = [];

    function dfs(node: TreeNode | null) {
        // Base case: if the node is null, we stop.
        if (!node) {
            return;
        }

        // Add the current node's value to the path.
        path.push(node.val);

        // If it's a leaf node, we've found a complete path.
        // Join the path elements and add to the result.
        if (!node.left && !node.right) {
            result.push(path.join('->'));
        } else {
            // If not a leaf, continue to children.
            dfs(node.left);
            dfs(node.right);
        }

        // Backtrack: remove the current node from the path when moving up the recursion tree.
        path.pop();
    }

    // Start the DFS from the root node.
    dfs(root);
    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.