• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Binary Tree in Java

April 9, 2015 by Dhaval Dave

How to write Binary Search Tree Code in Java with proper class structure and methods.

Here is the implementation of Binary Search Tree in Java.
Class Structure, Get Set Methods, Binary Tree Operation, Pre-Post-InOrder code and Testing Function is written Step by Step

ADT/Class Structure for Tree in java

Also Check this Best Books on Java 

class BinaryNode{
 private int Data;
 private Object Data;
 private BinaryNode Left;
 private BinaryNode Right;

 public BinaryNode(){ 
 Key = gio.ReadInteger("Enter in Key Value: ");
 Data = gio.ReadString("Enter in data : ");
 Left = null;
 Right = null;
 }
public class BTree
    {
    private BinaryNode Root;
    private int NoOfNodes;

    private BTree(){                                    
      Root = null;
      NoOfNodes = 0;
     }

Get Methods

public int gKey()
    {
    return Key;
    }

  public Object gData()
    {
    return Data;
    }

  public BinaryNode gLeft()
    {
    return Left;
    }
  public BinaryNode gRight()
    {
    return Right;
    }

Set Methods

public void sKey(int AValue)
    {
    Key = AValue;
    }

  public void sData(Object AValue)
    {
    Data = AValue;
    }

  public void sLeft( BinaryNode AValue)
    {
    Left = AValue;
    }

  public void sRight( BinaryNode AValue)
    {
    Right = AValue;
    }
}

Binary Tree Operations

public boolean IsEmpty(){
      return(NoOfNodes == 0);
      }
public BinaryNode gRoot()    {
      return Root; 
}
public int Count() { 
   return NoOfNodes; 
}
public int Size(BinaryNode ATree){
 if (ATree == null)
 return 0;
 else
 return(1 + Size(ATree.gLeft()) + Size(ATree.gRight()));
 }
public int Height(BinaryNode ATree){
 if (ATree == null)
 return 0;
 else
 return (1 + Math.max(Height(ATree.gLeft()), Height(ATree.gRight())));
 }

PreOrder PostOrder InOrder

public void PreOrder(BinaryNode ATree){
      if (ATree != null){
        System.out.println(ATree.gData());
        PreOrder(ATree.gLeft());
        PreOrder(ATree.gRight());
        }
      }

    public void InOrder(BinaryNode ATree){
      if (ATree != null){
        InOrder(ATree.gLeft());
        System.out.println(ATree.gData());
        InOrder(ATree.gRight());
        }
      }

public void PostOrder(BinaryNode ATree){
      if (ATree != null){
        PostOrder(ATree.gLeft());
        PostOrder(ATree.gRight());
        System.out.println(ATree.gData());
        }
      }

Insert Operation

public void Insert(int AId, Object AValue){ 
//For Binary Searh Tree //
      BinaryNode Temp,Current,Parent;
      if(Root == null){
        Temp = new BinaryNode(AId,AValue);
        Root = Temp;
        NoOfNodes++;
        }
      else {
        Temp = new BinaryNode(AId,AValue);
        Current = Root;
        while(true){
          Parent = Current;
          if(AId < Current.gKey())
            {
            Current = Current.gLeft();
              if (Current == null)
                {
                Parent.sLeft(Temp);
                NoOfNodes++;
                return;
                }
            }
          else
            {
            Current = Current.gRight();
            if(Current == null)
              {
              Parent.sRight(Temp);
              NoOfNodes++;
              return;
              }
            }
          }
        }

Search

public BinaryNode Find(int AKey)
      {
      BinaryNode Current = null;
      if(!IsEmpty())
        {
        Current = Root; 
        while(Current.gKey() != AKey)
          {
          if(AKey < Current.gKey())
            Current = Current.gLeft();
          else
            Current = Current.gRight();
          if(Current == null)
            return null;
          }
        }
        return Current;
      }

Main Method

public static void main (String [] Args)
    { 
    BTree MyTree = new BTree();                
    BinaryNode NodeAt;                           
    //Insert data into the tree - key and some text
    MyTree.Insert(12,"Hen");
    MyTree.Insert(4,"Dog");
    MyTree.Insert(11,"Cat");
    MyTree.Insert(1,"Frog");
    MyTree.Insert(100,"Owner");
    MyTree.Delete(1);
    MyTree.InOrder(MyTree.gRoot());       
    NodeAt = MyTree.Find(11);

    if(NodeAt !=null)
      System.out.println("Data in Node with Key 11 = " + NodeAt.gData());
    System.exit(0);
    }//end of test code
  }// end of class code

Similar Articles

Filed Under: Interview Questions, problem Tagged With: Java

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Binary Tree in Java

Python Dictionaries

Generate largest number arranging a no. of given non negative integer numbers

Find Percentage of Words matching in Two Strings

Serialise Deserialise N-ary Tree

Printing intermediate Integers between one element & next element of array

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Practo Hiring Experience

N teams are participating. each team plays twice with all other teams. Some of them will go to the semi final. Find Minimum and Maximum number of matches that a team has to win to qualify for finals ?

SAP Interview Questions

Hackerearth : Counting Subarrays

Best Java Book | Top Java Programming Book for Beginners

HackeEarth Flipkart’s Drone

Connect n ropes with minimum cost

Stickler thief

Find the smallest window in a string containing all characters of another string

Find Pythagorean Triplets in an array in O(N)

Knight Tour Problem (Graph – Breadth First Search)

Right view of Binary tree

SAP Off Campus Hiring_ March 2015 Verbal Skills

SAP Hiring Off-Campus General Aptitude

Top 10 Interviews Techniqes for Campus Interview in IIT NIT BITS for MTech

Given array of 0’s and 1’s. All 0’s are coming first followed by 1’s. find the position of first 1

Check if an array has duplicate numbers in O(n) time and O(1) space

The greedy coins game Dynamic Programming

Coin Collection Dynamic Programming

Introduction To Number Theory ( Part 1 )

Reliance Jio Software Developer Interview Experience

Puzzle : 100 doors in a row Visit and Toggle the door. What state the door will be after nth pass ?

Apriori algorithm C Code Data Mining

Copyright © 2025 · Genesis Framework · WordPress · Log in