Search code examples
javaarraysbinary-treebinary-search-tree

Storing Binary Tree into an array


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.


Solution

  • 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;
    }