15 Jun 2024C++ / Python / TypeScriptEasy

Binary Tree Paths

Collected C++, Python, TypeScript solutions for binary tree paths. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Binary Tree Paths. the solution files are available below.

solution files

  • C++ binary-tree-paths/synced-solution.cpp
  • Python binary-tree-paths/synced-solution.py
  • TypeScript binary-tree-paths/synced-solution.ts

Solution files

Pythonbinary-tree-paths/synced-solution.py
class TreeNode:
    def __init__(self, val=class="syntax-number">0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def binaryTreePaths(root: TreeNode) -> list[str]:
    result = []

    def dfs(node, path):
        if not node:
            return
        path += str(node.val)
        if not node.left and not node.right:
            result.append(path)
        else:
            if node.left:
                dfs(node.left, path + class="syntax-string">"->")
            if node.right:
                dfs(node.right, path + class="syntax-string">"->")

    dfs(root, class="syntax-string">"")
    return result
C++binary-tree-paths/synced-solution.cpp
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        string path = class="syntax-string">"";
        dfs(root, path, result);
        return result;
    }

private:
    void dfs(TreeNode* node, string path, vector<string>& result) {
        if (!node) return;
        path += to_string(node->val);
        if (!node->left && !node->right) {
            result.push_back(path);
        } else {
            if (node->left) dfs(node->left, path + class="syntax-string">"->", result);
            if (node->right) dfs(node->right, path + class="syntax-string">"->", result);
        }
    }
};
TypeScriptbinary-tree-paths/synced-solution.ts
function binaryTreePaths(root: TreeNode | null): string[] {
    const result: string[] = [];

    const dfs = (node: TreeNode | null, path: string): void => {
        if (!node) return;
        path += node.val;
        if (!node.left && !node.right) {
            result.push(path);
        } else {
            if (node.left) dfs(node.left, path + class="syntax-string">"->");
            if (node.right) dfs(node.right, path + class="syntax-string">"->");
        }
    };

    dfs(root, class="syntax-string">"");
    return result;
}