clueless coding // TODO: be smarter

LeetCode 257. Binary Tree Paths: Java Solution



Problem Statement


Given a binary tree, return all root-to-leaf paths.

Function Signature (Java):
  public List<String> binaryTreePaths(TreeNode root)

Inputs:
    1
   / \
  2   3
   \
    5

Outputs:
["1->2->5", "1->3"]



TL;DR Code Solution


public List<String> binaryTreePaths(TreeNode root) {
    List<String> answer = new ArrayList<String>();
    if (root != null) searchBT(root, "", answer);
    return answer;
}

private void searchBT(TreeNode root, String path, List<String> answer) {
    if (root.left == null && root.right == null) answer.add(path + root.val);
    if (root.left != null) searchBT(root.left, path + root.val + "->", answer);
    if (root.right != null) searchBT(root.right, path + root.val + "->", answer);
}