257 Binary Tree Paths
257. Binary Tree Paths
1. Question
1
/ \
2 3
\
5["1->2->5", "1->3"]2. Implementation
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
getTreePaths(root, "", res);
return res;
}
public void getTreePaths(TreeNode node, String curPath, List<String> res) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
res.add(curPath + node.val);
return;
}
getTreePaths(node.left, curPath + node.val + "->", res);
getTreePaths(node.right, curPath + node.val + "->", res);
}
}3. Time & Space Complexity
Last updated