#DYS – 4: Implementing binary search tree in Java

Posted: August 1, 2013 in Coding, DYS Series, Java

The below is a sample implementation of a binary search tree for all beginners out there. The code is pretty self-explanatory.

I shall come out with some interesting operations on the binary (search) tree from time to time basis.

package com.revindran.binarytree.utils;

public class BuildBinaryTree {
       
        static class Treenode{
              Treenode left;
              Treenode right;
              Integer nodeValue;
              
               public Treenode(Integer aValue){
                      this.nodeValue = aValue;
              }
                     
       }
       
        public static void addNode(Treenode rootnode, int value) {
               if (value rootnode.nodeValue) {
                      if (rootnode.right != null) {
                            addNode(rootnode.right, value);
                     } else {
                           rootnode. right = new Treenode(value);
                           System. out.println("Inserted " + value + " to the right of "
                                         + rootnode. nodeValue);
                     }

              }
       }
              
       
        public static void main(String[] args){
              Treenode node1 = new Treenode(5);
               addNode(node1, 6);
               addNode(node1, 1);
               addNode(node1, 7);
               addNode(node1, 4);
               addNode(node1, 3);
               addNode(node1, 0);
       }
       
}

 

Advertisements

Drop your thoughts here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s