257. Binary Tree Paths
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
helper(root, res, "");
return res;
}
private void helper(TreeNode root, List<String> res, String path) {
if (root == null) return; //terminator 1
path += root.val;
if (root.left == null && root.right == null) { //terminator 2
res.add(path);
}
helper(root.left, res, path + "->"); //drill down
helper(root.right, res, path + "->"); //drill down
}
}Last updated