2

This is code to get all the root to leaf paths in a Binary Tree but it puts in all the paths concatenated into one path. What is going wrong with the recursive call?

private void rec(TreeNode root,List<Integer> l, List<List<Integer>> lists) {
    if (root == null) return;

    if (root.left == null && root.right == null ) {
        l.add(root.val);
        lists.add(l);
    }

    if (root.left != null) {
        l.add(root.val);
        rec(root.left,l,lists);

    }
    if (root.right != null) {
        l.add(root.val);
        rec(root.right,l,lists);

    }

}
blanchey
  • 213
  • 2
  • 7

1 Answers1

1

You're reusing the same l list for all the paths, that won't work, you must create a new one every time the recursion gets called:

if (root.left != null) {
    List<TreeNode> acc = new ArrayList<>(l);
    acc.add(root.val);
    rec(root.left, acc, lists);
}

if (root.right != null) {
    List<TreeNode> acc = new ArrayList<>(l);
    acc.add(root.val);
    rec(root.right, acc, lists);
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386