0

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);
}  
4
  • 1
    Shouldn't inorder be left tree/elem/right tree? Commented Dec 11, 2014 at 9:30
  • Normally yes, but that would pull the nodes in ascending order. I'm going for descending. Commented Dec 11, 2014 at 9:32
  • I believe that the increments done to i in recursive calls do not modify it's value at the current level. Try using Integer i instead of int i in your method declaration. That might help. Commented Dec 11, 2014 at 9:42
  • @DušanRychnovský I get the same result. Index "i" seems to stay in the lower region of indices. If I insert 10 values into the tree and try to sort them, "i" never passes 3. Commented Dec 11, 2014 at 9:51

1 Answer 1

1

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;
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.