Description:
Given a binary tree, return all root-to-leaf paths.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
Code:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
traverse(root, new ArrayList<>(), paths);
return paths;
}
private void traverse(TreeNode root, List<String> path, List<String> paths) {
if (root == null) return;
path.add(""+root.val);
if (root.left == null && root.right == null) {
paths.add(String.join("->", path));
}
traverse(root.left, path, paths);
traverse(root.right, path, paths);
path.remove(path.size() - 1);
}
}