0

I am trying to create a rudimentary binary search tree in java with an insert and traverse method. The nodes have two local variables, a string and an int, the String value is used to sort the nodes.

Each BST has a local variable pointer to the root node and the nodes are inserted by traversing from the node. There seems to be a problem in creating the root node as my output is consistently producing null instead of.

THE CAT HAT

class BST
{
    public Node root = null;

    private class Node 
    {
        private String key;
        private int value;
        private Node left;
        private Node right;

        public Node ()
        {

        }

        public Node (String key, int value)
        {
            this.key = key;
            this.value = value;
        }

        public String toString ()
        {
            return ("The key is: "+ this.key +" "+ this.value);
        }
    }

    BST ()
    {
    }


    public void put (String key, int value)
    {
        put (root, key, value);
    }

    private void put (Node x, String key, int value)
    {
        Node newNode = new Node(key, value);

        if (x == null)
        {
            x = newNode;
            System.out.println("new node added");
            System.out.println(x);
        }

        int cmp = key.compareTo(x.key);

        if (cmp < 0)
            put(x.left, key, value);
        else if (cmp > 0)
            put(x.right, key, value);
        else
            x.value = value;

    }

    public void inorder (Node x)
    {
        if (x != null) 
        {
            inorder (x.left);
            System.out.println(x.key);
            inorder (x.right); 
        }

    }

    public static void main (String [] args)
    {
        BST bst = new BST();
        bst.put(bst.root,"THE", 1);
        bst.put(bst.root,"CAT", 2);
        bst.put("HAT", 1);
        bst.inorder(bst.root);

    }
}
1
  • 2
    You never assign anything to root. Commented Dec 18, 2018 at 5:36

4 Answers 4

1

Parameters are passed by value. Use the method's return value to alter something:

public void put (String key, int value)
{
    root = put (root, key, value);
}

private Node put (Node x, String key, int value)
{
    Node newNode = new Node(key, value);

    if (x == null)
    {
        System.out.println("new node added");
        System.out.println(x);
        return newNode;
    }

    int cmp = key.compareTo(x.key);

    if (cmp < 0)
        x.left = put(x.left, key, value);
    else if (cmp > 0)
        x.right = put(x.right, key, value);
    else
        x.value = value;

    return x;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Refer below link , good explanation of BST http://www.java2novice.com/java-interview-programs/implement-binary-search-tree-bst/

Comments

0

A binary search tree is a node-based data structure, the whole idea of a binary search tree is to keep the data in sorted order so we can search the data in a little faster.There are three kinds of nodes are playing key role in this tree (Parent Node,Left Child Node & Right Child Node).The value of the left child node is always lesser than the value of the parent node, the same as the value of the right child node is always greater than the value of the parent node. Each parent node can have a link to one or two child nodes but not more than two child nodes.

Please find the source code from my tech blog - http://www.algonuts.info/create-a-binary-search-tree-in-java.html

package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

class BinaryTreeNode {
    int nodeValue;
    BinaryTreeNode leftChildNode;
    BinaryTreeNode rightChildNode;

    public BinaryTreeNode(int nodeValue) {
        this.nodeValue = nodeValue;
        this.leftChildNode = null;
        this.rightChildNode = null;
    }

    public void preorder() {
        System.out.print(this.nodeValue+" ");
        if(this.leftChildNode != null)   {  
            this.leftChildNode.preorder();  
        }
        if(this.rightChildNode != null) {   
            this.rightChildNode.preorder();
        }
    }

    public void inorder() {
        if(this.leftChildNode != null) {    
            this.leftChildNode.inorder();   
        }
        System.out.print(this.nodeValue+" ");
        if(this.rightChildNode != null) {   
            this.rightChildNode.inorder();  
        }
    }

    public void postorder() {
        if(this.leftChildNode != null) { 
            this.leftChildNode.postorder();
        }
        if(this.rightChildNode != null) { 
            this.rightChildNode.postorder();
        }
        System.out.print(this.nodeValue+" ");
    }
}

class  BinaryTreeCompute {
    private static BinaryTreeNode temp;
    private static BinaryTreeNode newNode;
    private static BinaryTreeNode headNode;

    public static void setNodeValue(int nodeValue) {
        newNode = new BinaryTreeNode(nodeValue);
        temp = headNode;
        if(temp != null) 
        {   mapping();  }
        else 
        {   headNode = newNode; }
    }

    private static void mapping() {
        if(newNode.nodeValue < temp.nodeValue) {    //Check value of new Node is smaller than Parent Node
            if(temp.leftChildNode == null) 
            {   temp.leftChildNode = newNode;   }   //Assign new Node to leftChildNode of Parent Node
            else
            {
                temp = temp.leftChildNode;          //Parent Node is already having leftChildNode,so temp object reference variable is now pointing leftChildNode as Parent Node
                mapping();
            }
        }
        else
        {
            if(temp.rightChildNode == null) 
            {   temp.rightChildNode = newNode;  }   //Assign new Node to rightChildNode of Parent Node
            else
            {
                temp = temp.rightChildNode;         //Parent Node is already having rightChildNode,so temp object reference variable is now pointing rightChildNode as Parent Node
                mapping();
            }
        }
    }

    public static void preorder() {
        if(headNode != null) {  
            System.out.println("Preorder Traversal:");
            headNode.preorder();    
            System.out.println("\n");
        }
    }

    public static void inorder() {
        if(headNode != null) {
            System.out.println("Inorder Traversal:");
            headNode.inorder();
            System.out.println("\n");
        }
    }

    public static void postorder() {
        if(headNode != null) {
            System.out.println("Postorder Traversal:");
            headNode.postorder();   
            System.out.println("\n");
        }
    }
}

public class BinaryTree {
    //Entry Point
    public static void main(String[] args) {
        ArrayList <Integer> intList = new ArrayList <Integer>(Arrays.asList(50,2,5,78,90,20,4,6,98));   
        Iterator<Integer> ptr  = intList.iterator();
        while(ptr.hasNext()) 
        {   BinaryTreeCompute.setNodeValue(ptr.next()); }

        BinaryTreeCompute.preorder();
        BinaryTreeCompute.inorder();
        BinaryTreeCompute.postorder();

    }
}

Comments

-1

Adding to the answer by @Maurice,

Your code has several problems:

  1. You expect JAVA to be pass by reference, when it is pass by value. You should use the code given by Maurice instead.
  2. You are comparing "keys", when you should compare values.

I suggest that you use following modified code :

public class BST
{
    public Node root = null;

    private class Node
    {
        private String key;
        private int value;
        private Node left;
        private Node right;

        public Node ()
        {

        }

        public Node (String key, int value)
        {
            this.key = key;
            this.value = value;
        }

        public String toString ()
        {
            return ("The key is: "+ this.key +" "+ this.value);
        }
    }

    BST ()
    {
    }


    public void put (String key, int value)
    {
        root = putInTree (root, key, value);
    }

    private Node putInTree (Node x, String key, int value)
    {
        Node newNode = new Node(key, value);

        if (x == null)
        {
            x = newNode;
            System.out.println("new node added");
            System.out.println(x);
            return newNode;
        }

        //int cmp = key.compareTo(x.key);

        if (value < x.value)
            x.left = putInTree(x.left, key, value);
        else /*if (value >= x.value)*/
            x.right = putInTree(x.right, key, value);
        /*else
            x.value = value;*/

        return x;
    }

    public void inorder (Node x)
    {
        if (x != null)
        {
            inorder (x.left);
            System.out.println(x.key);
            inorder (x.right);
        }

    }

    public static void main (String[] args)
    {
        BST bst = new BST();

        bst.put("THE", 1);
        bst.put("CAT", 2);
        bst.put("HAT", 1);
        bst.inorder(bst.root);

    }
}

1 Comment

Thanks mate, the new flow is a complete improvement. Learned a lot.

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.