The Binary Tree Paths solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Binary Tree Paths
C++, Python and TypeScript solutions for Binary Tree Paths.
Solution files
Python•binary-tree-paths/synced-solution.py
class TreeNode:
def __init__(self, val=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 + "->")
if node.right:
dfs(node.right, path + "->")
dfs(root, "")
return result
C++•binary-tree-paths/synced-solution.cpp
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path = "";
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 + "->", result);
if (node->right) dfs(node->right, path + "->", result);
}
}
};
TypeScript•binary-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 + "->");
if (node.right) dfs(node.right, path + "->");
}
};
dfs(root, "");
return result;
}