Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 12, 2017 23:17
Show Gist options
  • Save shailrshah/1b2b1c5b5053337862dd6ac54a03232e to your computer and use it in GitHub Desktop.
Save shailrshah/1b2b1c5b5053337862dd6ac54a03232e to your computer and use it in GitHub Desktop.
Given a binary tree, return all root-to-leaf paths.
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
if(root != null)getPaths(root, list, "");
return list;
}
private static void getPaths(TreeNode root, List<String> list, String path) {
if(root.left == null && root.right == null) list.add(path + root.val);
if(root.left != null) getPaths(root.left, list, path + root.val + "->");
if(root.right != null) getPaths(root.right, list, path + root.val + "->");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment