Click here to Skip to main content
15,358,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm supposed to create a binary search tree that takes in integer array, I want to know how can I access the left and right nodes in Node class to create the left and right nodes, please assist This is the Node class


private int element;
private BinaryNode left;
private BinaryNode right;
public Node( ){
    this( 0, null, null );}
public( int theElement, BinaryNode lt, BinaryNode rt ){
    element = theElement;
    left    = lt;
    right   = rt;}
public int getElement( ){
    return element;}
public BinaryNode getLeft( ){
    return left;}
public BinaryNode getRight( ){
    return right;}
public void setElement( int x ){
    element = x;}
public void setLeft( BinaryNode t ){
    left = t;}

public void setRight( BinaryNode t ){
    right = t;}


What I have tried:

static Node obj = new Node();
static Node root = new Node();
static Node BinaryTree(int[] array, int begin, int end){
        if(begin > end){  //checks in the array is still in bound
            return null;  //returns null so the next node can be null
        }

        int middle = (begin + end)/2;  //finds the middle index
        obj.setElement(array[middle]);
        root = new Node(obj.getElement(), obj.getLeft(), obj.getRight()); //creates the root node of the tree/subtree
        root.setLeft(BinaryTree(array, begin, middle-1)); //creates the left tree or node recursively
        root.setRight(BinaryTree(array, middle+1, end));  //creates the right tree or node recursively
        return root; //places/returns the node of the tree in its place
    }
Posted
Updated 13-May-21 22:57pm

1 solution

Without your data, we can't even begin to check what you are actually doing.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900