-1

I written an binary tree with post order, but I got some error message..

error picture

 public static void main(String [] args) {
    int input;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the number of the data: ");
    input = sc.nextInt();
    int[] data;

    data = new int[input];
    BSTree tree = new BSTree();
    System.out.println("Enter the values: ");
        for (int i = 0; i < input; i++) {
            data[i] = sc.nextInt();
        }
            System.out.print(data + " ");
            tree.insert(data[input]);
        System.out.println();

        System.out.println("It used preorder.");
        System.out.println("BinarySearchTree - size: " + tree.size() + " height: " + tree.height());
        tree.postorder();   // left right root

I can store 5 number now. But now I can't show the my inserted data and the post order, whats going on?

    public static void main(String [] args) {
int input;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of the data: ");
input = sc.nextInt();

int[] data = new int[input];
BSTree tree = new BSTree();
System.out.println("Enter the values: ");
    for (int i = 0; i < data.length; i++) {
        data[i] = sc.nextInt();
    }
        System.out.print(data + " ");
        tree.insert(input);

    System.out.println("It used preorder.");
    System.out.println("BinarySearchTree - size: " + tree.size() + " height: " + tree.height());
    tree.postorder();

I prefer will show Inserted : 33 44 22 11 23 postorder :

and now show

   Enter the number of the data: 5
Enter the values:
32
23
13
12
4
[I@5b6f7412 It used preorder.
BinarySearchTree - size: 1 height: 0
5
erictc
  • 15
  • 5
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – OH GOD SPIDERS Dec 01 '20 at 15:44
  • Please don't post screenshots of your error, just post the text. – rhowell Dec 01 '20 at 15:45
  • @rhowell thanks for remind. – erictc Dec 01 '20 at 16:17

1 Answers1

1

Here is mistake.

tree.insert(data[input]);

For example, if input is 5, then

data = new int[input];

Creates an array of 5 elements, with last index of 4. So data[5] will throw such exception.

P.s. in your screenshot there is a line number of mistake =)

Ilya Mezhov
  • 111
  • 4