1

I attempting to store a binary tree into an array with the code below:

public void inorderArray(int[] array)  {
       inorderArray(root, array, 0);
}

private static Integer inorderArray(TreeNode root, int[] array, int index) { 
    // an inorder traversal that stores the items in array
    if(root == null){return index;}

    inorderArray(root.left, array, index);
    array[index++] = root.key;
    inorderArray(root.right, array, index);

    return index;
}

I keep getting [94, 95, 0, 0, 0, 0, 0, 0, 0, 0], and its not in order either.

I have no idea what I am doing wrong. Any help is appreciated.

1
  • as a side note - no need to return Integer, just int would suffice. Commented Nov 5, 2017 at 18:53

1 Answer 1

2

You are not using the return value. And you need to use it, because the modification in index++ would never leave the scope of the function.

private static int inorderArray(TreeNode root, int[] array, int index) {
    if (root == null) {
        return index;
    }

    index = inorderArray(root.left, array, index);
    array[index++] = root.key;
    index = inorderArray(root.right, array, index);
    return index;
}
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.