Reputation: 1
I am trying to traverse a Binary Tree in descending inorder style and copy the elements to an array. I believe I am 80% there, I just can't seem to figure out what's going on with my index. Any help or pointers in the right direction are appreciated.
public static void inorder(int[] a) {
int i = 0;
// call recursion
inorder(root, a, i);
System.out.println("Array: ");
for (int j = 0; j < a.length; j++) {
System.out.println(a[j]);
}
}
private static void inorder(Node temp, int[] a, int i) {
// base case
if (temp == null) return;
// go to the right of tree
inorder(temp.right, a, i);
// copy node to array
a[i] = temp.number;
System.out.println(temp.number);
System.out.println(i);
i++;
// go to the left of tree
inorder(temp.left, a, i);
}
Upvotes: 0
Views: 2748
Reputation: 967
try updating i and returning its value
private static int inorder(Node temp, int[] a, int i) {
// base case
if (temp == null) return i;
// go to the right of tree
i = inorder(temp.right, a, i);
// copy node to array
a[i] = temp.number;
System.out.println(temp.number);
System.out.println(i);
i++;
// go to the left of tree
i = inorder(temp.left, a, i);
return i;
}
Upvotes: 1