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
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.
binary-tree-paths/synced-solution.cppbinary-tree-paths/synced-solution.pybinary-tree-paths/synced-solution.tsclass 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
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);
}
}
};
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;
}