Trying to insert strings from array into a binary search tree

Viewed 40

I'm trying to make the root the [0] position of the array and then divide the remaining elements in half and start one half as the left branch and the other half as the right branch.

here is the Node class my issue is as I create a new node it is not being linked to the root and when I go to display the tree starting at the root it throws the null pointer exception.

static class Node {
//      public int iData;     // data item (key);
        public String dData; // data item
        public Node left;
        public Node right;

        public Node(String data) {
            this.dData = data;

        }
        public Node getLeft() {
            return left;
        }
        public Node getRight() {
            return right;
        }
        public String getData() {
            return dData;
        }

        public void displayNode() {
            System.out.println("{" + dData + "}");
        }
    }// end Node

public void insert(Node root) {
    int max, min, mid;
    min = 1;
    max = elementArray.length - 1;
    mid = (int) (Math.ceil(min + max) / 2);
    root = new Node(elementArray[0]);
    System.out.println(elementArray[0] + " is element added to root");
    insert(root.left, elementArray, min, mid);
    insert(root.right, elementArray, ++mid, max);
}

public void insert(Node parent, String[] elements, int min, int max) {
    int mid = (int) (Math.floor((min + max) / 2));
    if (min == max) {
        return;
    }
    System.out.println(min + " " + max + " " + mid); // check outputs
    parent = new Node(elements[mid]);
    insert(parent.left, elements, min, mid);
    insert(parent.right, elements, ++mid, max);
    System.out.println(elements[mid] + " is element added to tree"); // check inputs
}
0 Answers
Related