I was trying to solve a problem:
Print all paths of a binary tree, from root to leaf.
I wrote the following code, the result is correct:
public void printPath(TreeNode root) {
printDFS(root, new int[1000], 0);
}
private void printDFS(TreeNode r, int[] path, int idx){
if (r == null) return;
path[idx] = r.val;
idx++;
/* if it's leaf, print path: from root to leaf */
if (r.left == null && r.right == null)
printOnePath(path, idx);
else {
/* go left, go right */
printDFS(r.left, path, idx);
printDFS(r.right, path, idx);
}
}
private void printOnePath(int[] path, int idx) {
for (int i = 0; i < idx; i++) {
System.out.print(path[i] + " ");
}
System.out.println();
}
However,
when I tried to use ArrayList to store the path data, instead of int[].
This method becomes wrong.
And the output results really lost me.
public void printPath(TreeNode root) {
printDFS(root, new ArrayList<Integer>(), 0);
}
private void printDFS(TreeNode r, List<Integer> path, int idx){
if (r == null) return;
path.add( r.val );
idx++;
/* if it's leaf, print path: from root to leaf */
if (r.left == null && r.right == null)
printOnePath(path, idx);
else {
/* otherwise: go left, go right */
printDFS(r.left, path, idx);
printDFS(r.right, path, idx);
}
}
private void printOnePath(List<Integer> path, int idx) {
for (int i = 0; i < idx; i++) {
System.out.print(path.get(i) + " ");
}
System.out.println();
}
E.g:
First STDOUT is: (Correct)
10 5 3 3
10 5 3 -2
10 5 2 1
10 -3 11
Second STDOUT is: (Wrong)
10 5 3 3
10 5 3 3
10 5 3 3
10 5 3
I believe the initial ArrayList has already set as empty at the very beginning of each DFS. Why is the result totally different with an int array, even using the same method?
Does anyone know why? Thanks a lot!