问题
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);
}
}
回答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);
}
来源:https://stackoverflow.com/questions/48132359/binary-search-tree-path-list