Binary Tree search and print methods

Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
public class TreeNode 
      public static String empName = null;
      public static int empNumber;
      public static String nextRec = null;
          TreeNode left;
      String Name;
      int Number;
      TreeNode right;
      public static void main(String[] args)
         VRead in = new VRead();
         VWrite out = new VWrite();
         System.out.println("Enter Choice: ");
         System.out.println("A: Enter Employee Information.");
         System.out.println("B: Search For Employee.");
         System.out.println("C: Print Entire Tree.");
         System.out.println("D: Exit.");
         System.out.println("_______________________________");
         char command = in.readChar();
         System.out.println();
         switch (command)
            case 'A':
            case 'a':
               inputInfo(in, out);           
               break;
            case 'B':
            case 'b':
               break;
            case 'C':
            case 'c':
               break;
            case 'D':
            case 'd':
               System.exit(0);
               break;
      public static void inputInfo(VRead in, VWrite out)
         out.write("Enter Employee Name: ");
         empName = in.readString();
         out.write("Enter Employee Number: ");
         empNumber = in.readInt();
         System.out.println();
         System.out.println();
         System.out.println("Enter Choice: ");
         System.out.println("A: Enter Employee Information.");
         System.out.println("B: Search For Employee.");
         System.out.println("C: Print Entire Tree.");
         System.out.println("D: Exit.");
         System.out.println("_______________________________");
         char command = in.readChar();
         System.out.println();
         switch (command)
            case 'A':
            case 'a':
               inputInfo(in, out);           
               break;
            case 'B':
            case 'b':
               break;
            case 'C':
            case 'c':
                         break;
            case 'D':
            case 'd':
               System.exit(0);
               break;
      public TreeNode(String empName, int empNumber)
         Name = empName;
         Number = empNumber;
         left = null;
         right = null;
      public class Tree
         TreeNode Root;
         public void Tree(String RootNode)   
    // Errors come from next line
              Root = new TreeNode(RootNode, Name, Number);   
         public void Insert(String Name, int Number)
            InsertNode(Root, Name, Number);
         public void InsertNode(TreeNode t, String empName, int empNumber)
            if (t == null)
               t = new TreeNode(empName, empNumber);
            else
               if (empName.compareTo(t.Name) < 0)
                  InsertNode(t.left, empName, empNumber);
               else if (empName.compareTo(t.Name) > 0)
                  InsertNode(t.right, empName, empNumber);
               else if (empName.compareTo(t.Name) == 0)
                  System.out.println("Entered node that was already in Tree");
   }im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method too

Just having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
FWIW
I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
*Before anyone flames, it's a joke
G

Similar Messages

  • Binary Tree Search

    Hi everyone,
    I have an assignment :Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search.
    And I did it in the folloiwng but there some problems that I encounter.When I execute the following code, there is an exception occurs. It says that my left BinaryTree is null. So why ???
    Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search

    Hi,
    I changed the old codes to the below. I think this is orrect logically for binary trees.
    If not, please explain why ??
    import java.util.*;
    class BinaryTree {
         // properties
         ArrayList store;
         BinaryTree left;
         BinaryTree right;
         int root;
         int valuesLeft = 1;      // for adding the left root
         int valuesRight = 1;     // for adding the right root
         // constructors
         // first constructor
         public BinaryTree(BinaryTree left, BinaryTree right){          
              store = new ArrayList();
              root = 12;
              store.add( new Integer(root));  // root value
              this.left = left;
              this.right = right;
         // second constructor
         public BinaryTree(){
              store = new ArrayList();
         // methods
         public void insert(int a){
              if(a < ( (Integer)(store.get(0)) ).intValue()){
                   setLeft(a);
              else{
                   setRight(a);
         public void setLeft(int node){
              if(valuesLeft == 1)
                   root = node;
              (left.store).add(new Integer(node) );
              valuesLeft++;
         public void setRight(int node){
              if(valuesRight == 1)
                   root = node;
              (right.store).add(new Integer(node) );
              valuesRight++;
         public int search(int value){
              if(value == root){
                   return value;
              else if(value < root){
                   return left.search(value);
              else if(value > root)
                   return right.search(value);
              else
                   return -1;     
    //     public String toString(){
         public static void main( String[] args)
              BinaryTree leftTree = new BinaryTree();
              BinaryTree rightTree = new BinaryTree();
              BinaryTree root = new BinaryTree(leftTree, rightTree);
              root.insert(5);     
              root.insert(15);
              root.insert(6);          
              root.insert(3);          
              root.insert(51);
              root.insert(2);     
              root.insert(115);
              root.insert(7);          
              root.insert(33);          
              root.insert(511);               
              root.search(15);     
    }

  • Script to Search and Print

    Hi.
    I would like to automate the search of a pdf document and the subsequent printing (or extraction) of all the pages on which the searched text appears.  I think a script would be appropriate but I have no idea where to begin,  Can someone help me with this?  I deal routinely with large, mostly text pdf documents where I need to print many non-sequential pages.
    Thanks

    this piece of script will help you get there:
    [code]
    set search_for to "part" ---search for this name
    set search_here to POSIX path of (path to desktop folder) as string ---- too much to handle
    set search_here to "/Users/timmason/Desktop/spotlight scripts/csacsacs/alta__001 copy 2.pdf" ------file to search -not working
    set search_here to "/Users/timmason/Desktop/spotlight scripts/csacsacs/" ------folder to search
    display dialog searcher(search_for, search_here) ---returns location of doc
    on searcher(search_for, search_here)
    set the_script to {"mdfind -onlyin '", search_here, "' '", search_for, "'"} as string --converted for vars
    set the_text to (do shell script the_script)
    set num_records to count of paragraphs in the_text
    set x to 0
    set all_recs to ""
    repeat num_records times
    set x to x + 1
    set all_recs to all_recs & return & return & paragraph x of the_text
    end repeat
    return all_recs
    end searcher

  • Searching and printing from address book

    Is there a way to do a find or sort on an address book field? That is, I'd like to find within "all" or a specific group which entries have (or don't have) an e-mail address associated with it. I'm aware that I can choose fields to display when printing, but it's not quite what I need. Is this a case for scripting or exporting? Or am I overlooking something really obvious? Thanks for any tips.

    Sorry, you can't do that. You can only search for text found in a name field for a card or group of cards, not for anything else.
    Mulder

  • Search for record in txt and print to console

    QairNo: 21, PostCd: 12, Age: 21, Gender: 2, Q1Res: 1, Q2Res: 2, Q3Res: 3,
    QairNo: 23, PostCd: 21, Age: 12, Gender: 2, Q1Res: 1, Q2Res: 2, Q3Res: 3,
    QairNo: 32, PostCd: 32, Age: 12, Gender: 1, Q1Res: 2, Q2Res: 1, Q3Res: 2, Hi i manage to write the above entry into database.txt
    now i need to search and print the particular data i need. For example i enter *21* and it will print all the attribute that belong to it.
    Please forgive me i am new to this, i have google for example but i can`t apply them for some reason. Below are my code, thank you for helping out !
    public class PollSummary {
         public static void main (String args[]) throws IOException {
              //int inputQuestionNum= 0;
              String key = "QairNo: ";
              Scanner input = new Scanner(new FileReader("polldata.txt"));
              while(input.hasNextLine()){
                   System.out.println(input.nextLine());
              //System.out.println("Enter the Questionnaire Number to view records");
              //inputQuestionNum = Integer.parseInt(entry.nextLine());
               while (input.hasNext() && input.findInLine(key) != null)
                     String fileLine = input.nextLine();
                     System.out.println(fileLine);
         }//end main
    }//end class

    You should use a map, just use the QuairNo as a key (aside: what is a Quair?)
    http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html

  • Store+search+view+print inventory,store+search+print rent information

    Good morning,
    I need some help regarding my Java Project. I was told by my lecturer to do one program[probably java applets] to store all informations about CDs and Videos.
    The program should be able to :
    1)store,view,search and print the informations of CDs and Videos.
    2)store,view,search and print the informations of customers
    This are the informations that need to be stored for:
    CDs:
    1. Title of album
    2. artist
    3. number of tracks
    4. total playing time
    5. comments
    Videos:
    1. Title of video
    2. Name of director
    3. total playing time
    4. comment
    For search CDs and Vidoes information, user will key in the artist name(for CDs) and director name (for video)
    For the renting section:
    1)the employee will be able to key in customer transaction.
    2) The customer must be a member to rent the CDs and Videos.If not, he / she must registers first.
    3)The transaction will be recorded in terms of the CDs/Videos informations, date of rent,due date and payments.
    4)The applet must also can identify which customer that has not pay/not return yet. If he or she does not return yet, he or she wont be able to rent .
    Here is some of coding that I have made:
    Name:TestRandomAccessFile[only for Videos]
    *i dont know how to combine CDs.
    *This applet coding only consists of register informations about Videos and View ONLY
    //TestRandomAccessFile.java: Store and read data
    //using RandomAccessFile
    package Store;
    import java.io.*;
    import java.awt.*;
    import java awt.event.*;
    import javax.swing.*;
    import CHapter9.MyFrameWithExitHandling;
    import javax.swing.border.*;
    public class TestRandomAccessFile extends MyFrameWithExitHandling
         //Create a tabbed pane to hold two panels
         private JTabbedPane jtpVideo = new JTabbedPane ();
         //Random access file for access the student.dat file
         private RandomAccessFile raf;
         //Main method
         public static void main (STring[]args)
         TestRandomAccessFile frame = new TestRandomAccessFile ();
         frame.pack ();
         frame.setTitle ("Test Random Access File");
         frame.setVisible ("True");
         //Default constructor
         // Open or create a random access file
         try
         raf=new RandomAccessFile("video.dat","rw");
         catch(IOException ex)
         System.out.print ("Error: " + ex);
         System.exit (0);
         //Place buttons in the tabbed pane
         jtpVideo.add (new RegisterVideo(raf),"Register Video");
         jtpVideo.add (new ViewVideo(raf),"View Video");
         //Add the tabed pane to the frame
         getContentPane().add(jtpVideo);
         //Register video panel
         class RegisterVideo extends Jpanel implements ActionListener
         //Button for registering a video
         private JButton jbtRegister;
         //Video information panel
         private VideoPanel videoPanel;
         //Random access file
         private RandomAccessFile raf;
         //COnstructor
         public RegisterVideo (RandomAccessFile raf)
         //Pass raf to RegisterVideo Panel
         this.raf=raf;
         //Add videoPanel and jbtRegister in the panel
         setLayout Pnew BorderLayout ());
         add (videoPanel= new VideoPanel(),BorderLayout.CENTER);
         add(jbtRegister= new JButton ("Register"),BorderLayout.SOUTH);
         //Register listener
         jbtRegister.addActionListener(this);
         //Handle button actions
         public void actionPerformed(ActionEvent e)
         if (e.getSource()==jbtRegister)
         Video video=videoPanel.getVideo();
         try
         raf.seek(raf.length());
         video.writeVideo(raf);
         catch (IOException ex)
         System.out.print ("Error:" + ex);
         //View video panel
         class ViewVideo extends JPanel implements ActionListener
         //Buttons for viewing video information
         private JButton jbtFirst,jbtNext,jbtPrevious,jbtLast;
         //Random access file
         private RandomAccessFile raf=null;
         //Current Video Record
         private Video video = new Video ();
         //Create a Video panel
         private StudentPanel studentPanel=new StudentPanel ();
         //File pointer in the random access file
         private long lastPos;
         private long currentPos;
         //Contsructor
         public ViewVideo (RandomAccessFile raf)
         //Pass raf to ViewVideo
         this.raf=raf;
         //Panel p to hold four navigation buttons
         JPanel p=new Jpanel();
         p.setLayout(new FlowLayout(FlowLayout.LEFT));
         p.add(jbtFirst=new JButton("First"));
         p.add(jbtNext=new JButton("Next"));
         p.add(jbtPrevious=new JButton("Previous"));
         p.add(jbtLast=new JButton("Last"));
         //Add panel p and studentPanel to ViewPanel
         setLayout(new BorderLayout());
         add(studentPanel;BorderLayout.CENTER);
         add(p,BorderLayout.SOUTH);
         //Register listeners
         jbtFirst.addActionListener(this);
         jbtNext.addActionListener(this);
         jbtPrevious.addActionListener(this);
         jbtLast.addActionListener(this);
         //Handle navigation button actions
         public void actionPerformed(ActionEvent e)
         String actionCommand=e.getActionCommand();
         if(e.getSource() instanceof JButton)
         try
         if ("First".equals(actionCommand))
         if(raf.length()>0)
         retrieve(0)l
         else if ("Next".equals(actionCommand))
              currentPos=raf.getFilePointer();
              if (currentPos<raf.length())
         retrieve(currentPos);
         else if ("Previous".equals(actionCommand))
              currentPos=raf.getFilePointer();
              if (currentPos<raf.length())
         retrieve(currentPos-2*2*Video.RECORD_SIZE);
         else if ("Last".equals(actionCommand))
              lastPos=raf.getFilePointer();
              if (lastPos<raf.length())
         retrieve(lastPos-2*Video.RECORD_SIZE);
         catch (IOException ex)
         System.out.print("Error:"+ex);
         //Retrive a RECORD at specific position
         public void retrieve(long pos)
         try
         raf.seek(pos);
         video.readVideo(raf);
         videoPanel.setVideo(video);
         catch (IOException ex)
         System.out.print ("Error lagi la wei:"+ex);
         //This class contains static method to read and write fixed length      //records
         class FixedLengthStringTo
         //Read fix number of the chracter from DataInput stream
         public static String readFixedLengthString(int size;DataInput in)
         throws IOException
         char c[]=new char [size];
         for (int=0;i<size;i++)
         c=in.readChar();
         return new String(c);
         //Write fixed number of chracter (string with padded space
         //to DataOutput Stream
         public static void writeFixedLengthString (String s,int size, Data.Output out) throws IOException
         char cBuffer[]=new char[size];
         s.getChars(0,s.length(),cBuffer,0);
         for (int i=s.length();i<cBuffer.length;i++)
         cBuffer[i]=' ';
         String newS=new String (cBuffer);
         out.writeChars(newS);
    File name:CD
    package Kedai;
    import java.io.*;
         public class CD
         private String title;
         private String artist;
         private String tracks;
         private String time;
         private String comment;
         //Specify the size of four string fileds in record
         final static int TITLE_SIZE=32;
         final static int ARTIST_SIZE=32;
         final static int TRACKS_SIZE=20;
         final static int TIME_SIZE=10;
         final static int COMMENT_SIZE=40;
         //the total size of the record un bytes,a Unicode
         //character is 2 bytes size
         final static int RECORD SIZE= (TITLE_SIZE+ARTIST_SIZE+TRACKS_SIZE+TIME_SIZE+COMMENT_SIZE);
         //Default constructor
         public CD()
         //Construct with specified data
         public CD (String title,String artist,String tracks,String time,String comment)
         this.title=title;
         this.artist=artist;
         this.tracks=tracks;
         this.time=time;
         this.comment=comment;
         public String getTitle()
         return title;
         public String getArtist()
         return artist;
         public String getTracks()
         return tracks;
         public String getTime()
         return time;
         public String getComment()
         return comment;
    //Write a CD to a data output stream
    public void writeCD (DataOutput out) throws IOException
    FixedLengthStringIO.writeFixedLengthString(title,TITLE_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(artist,ARTIST_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(tracks,TRACKS_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(time,TIME_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(comment,COMMENT_SIZE,out);
    //Read CD from data input stream
    public void readCD(DataInput in) throws IOException
    title=FixedLengthStringIO.readFixedLengthString(TITLE_SIZE,in);
    artist=FixedLengthStringIO.readFixedLengthString(ARTIST_SIZE,in);
    tracks=FixedLengthStringIO.readFixedLengthString(TRACKS_SIZE,in);
    time=FixedLengthStringIO.readFixedLengthString(TIME_SIZE,in);
    comment=FixedLengthStringIO.readFixedLengthString(COMMENT_SIZE,in);
    File name:Video
    package Kedai;
    import java.io.*;
         public class Video
         private String title;
         private String director;
         private String time;
         private String comment;
         //Specify the size of four string fileds in record
         final static int TITLE_SIZE=32;
         final static int DIRECTOR_SIZE=32;
         final static int TIME_SIZE=10;
         final static int COMMENT_SIZE=40;
         //the total size of the record un bytes,a Unicode
         //character is 2 bytes size
         final static int RECORD SIZE= (TITLE_SIZE+DIRECTOR_SIZE+TIME_SIZE+COMMENT_SIZE);
         //Default constructor
         public Video()
         //Construct with specified data
         public Video (String title,String director,String time,String comment)
         this.title=title;
         this.director=director;
         this.time=time;
         this.comment=comment;
         public String getTitle()
         return title;
         public String getDirector()
         return director;
         public String getTime()
         return time;
         public String getComment()
         return comment;
    //Write a video to a data output stream
    public void writeVideo (DataOutput out) throws IOException
    FixedLengthStringIO.writeFixedLengthString(title,TITLE_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(director,DIRECTOR_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(time,TIME_SIZE,out);
    FixedLengthStringIO.writeFixedLengthString(comment,COMMENT_SIZE,out);
    //Read video from data input stream
    public void readVideo(DataInput in) throws IOException
    title=FixedLengthStringIO.readFixedLengthString(TITLE_SIZE,in);
    director=FixedLengthStringIO.readFixedLengthString(DIRECTOR_SIZE,in);
    time=FixedLengthStringIO.readFixedLengthString(TIME_SIZE,in);
    comment=FixedLengthStringIO.readFixedLengthString(COMMENT_SIZE,in);
    I need help in terms of:
    1)store,view,search and print the informations of CDs and Videos.
    2)store,view,search and print the informations of customers
    What should I modify my coding above?What should I do next?Can anyone give me the code since I'm not good enough in creating Java coding.Please. The submission is on 30 September

    You made three mistakes:
    1) You posted to a JSP/JSTL forum when asking about applet code. Maybe you should redirect your thread to a more appropriate forum - Like one for Applets or general Java Programming.
    2) You waited for the last few days to try tosolve your problem. If you spent time working on it little by little you would be closer to a solution.
    3) You begged for someone to do the work for you. Asking for help is one thing. That I was willing to do, even though you posted to the wrong forum, but then you said: "someone do it for me because I am not good enough" which really means: "Someone help me cheat and hand in your work as my own because I am too lazy to do it myself."
    If you can't do the work, maybe you should drop the course.

  • Help with a binary tree

    I'm writing a binary tree class and am having some trouble with the Insert function. Here is the code for the TreeNode class...
    public class TreeNode
         TreeNode Left;
         TreeNode Right;
         String Name;
         public TreeNode(String NodeName)
              Left = null;
              Right = null;
              Name = NodeName;
    }And this is the code for the Tree class...
    public class Tree
         TreeNode Root;
         public Tree(String RootNode)
              Root = new TreeNode(RootNode);
         public void Insert(String Name)
              InsertNode(Root, Name);
         public void InsertNode(TreeNode t, String NodeName)
              if (t == null)
                   t = new TreeNode(NodeName);
              else
                   if (NodeName.compareTo(t.Name) < 0)
                        InsertNode(t.Left, NodeName);
                   else if (NodeName.compareTo(t.Name) > 0)
                        InsertNode(t.Right, NodeName);
                   else if (NodeName.compareTo(t.Name) == 0)
                        System.out.println("Entered node that was already in Tree");
    }When I enter a new node into a Tree containing just the root, it follows the recursion through once, then creates the new TreeNode as it should. However, the new node is not really recognized by the tree because when I try to insert another node, it only finds the root in the tree and only goes through one recursion. What's wrong?

    I believe t.Left (or t.Right) is getting set in the line
    t = new TreeNode(NodeName);
    Since it is a recursive function, when it is called the second time, the "t" that is passed in is actually the original t.left (I think), which is getting set then.

  • How to Pretty Print a Binary Tree?

    I'm trying to display a Binary Tree in such a way:
    ________26
    ___13_________2
    1_______4 3_________1
    (without the underscores)
    however I cannot figure out the display method.
    class BinaryNode
              //Constructors
              BinaryNode leftChild, rightChild;
    Object data;
         BinaryNode()
    leftChild = null;
    data = null;
    rightChild = null;
              BinaryNode( Object d, BinaryNode left, BinaryNode right)
    leftChild = left;
    data = d;
    rightChild = right;
              //Height
              public static int Height(BinaryNode root)
    if (root == null)
    return 0;
    if ((Height(root.leftChild)) > Height(root.rightChild))
    return 1 + Height(root.leftChild);
    return 1 + Height(root.rightChild);
              //Count
    public static int Count(BinaryNode root)
    if(root==null)
    return 0;
    return 1 + Count(root.leftChild) + Count(root.rightChild);
              //Display
              public static void Display(BinaryNode root)
              int level = 2^(Level(root)-1)
              for (int i = 1; i<Height(root)+1; i++)
              System.out.printf("%-4s%
              Display(root, i);
              System.out.println();
              public static void Display(BinaryNode root, int level)
              if (root!=null)
              if(level==1)
              System.out.print(root.data + " ");
              else
              Display(root.leftChild, level-1);
              Display(root.rightChild, level-1);
              //Level
              public static int Level(BinaryNode root)
              if(root==null)
              return 0;
              if(root.leftChild == null && root.rightChild == null)
              return 1;
              return Level(root.leftChild) + Level(root.rightChild);
    Edited by: 815035 on Nov 23, 2010 12:27 PM

    The example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
    Unfortunately it is also quite difficult to accomplish using System.out.print statements.
    You have to print out the root of the tree first (its at the top)
    However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
    So you will need to traverse the tree at least twice.
    Once to work out the offsets, and again to print out the values.
    The working out of offsets would have to be a depth search traversal I think
    The printing of the values in this fashion would be a breadth first traversal.
    I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
    ie the root was on the left, the leaves of the tree on the right of the screen.
    That meant you could do an inorder depth traversal of the tree to just print it once.
    hope this helps,
    evnafets

  • Searching for a certain  binary tree from another tree........

    I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
    Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
    Tree B has a similar structure.
    The node used for both A and B.
    Node{
    Node left;
    Node right;
    My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
    So, the method should look like:
    public Node search(Node rootOfA, Node rootOfB){
    I know a simple recursive fuction can do the job. The question is all about the effciency....
    I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
    Anyone knows of that? Any friend can give a sound solution?
    Thank you all in advance.
    Jason
    Message was edited by:
    since81

    I'm not too sure if this would help but there goes.
    I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
    Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.
    :)

  • Java binary search and insert

    I'm currently writing a program which is an appointment book. I currently have 4 classes and at the minute it can sort the array and print it out. I'm stuck at binary search and inserting a new appointment record. I will include the classes which i have got.
    Appointment
       import java.util.*;
       import java.io.*;
       import java.util.Scanner;
        class Appointment implements Comparable
          private String description;
          private int day;
          private int month;
          private int year;
          private String startTime;
          private String endTime;
          protected static Scanner keyboard = new Scanner(System.in);     
           public Appointment()
             description = "";
             day = 0;
             month = 0;;
             year = 0;;
             startTime = "";
             endTime = "";
           public Appointment(String appDesc, int appDay, int appMonth, int appYear, String appStartTime, String appEndTime)
             description = appDesc;
             day = appDay;
             month = appMonth;
             year = appYear;
             startTime = appStartTime;
             endTime = appEndTime;
           public void display()      
             System.out.print("  Description: " + description);
             System.out.print(", Date: " + day + "/" +month+ "/" +year);
             System.out.println(", Start Time: " + startTime);
             System.out.println(", End Time: " + endTime);
           public void setDay(int day)
          { this.day = day; }
           public int getDay()     
             return day; }
           public void setMonth(int month)
          { this.month = month; }
           public int getMonth()     
             return month; }
           public void setYear(int year)
          { this.year = year; }
           public int getYear()
             return year; }
           public int compareTo(Object obj)
             if (obj instanceof Appointment)
                Appointment appt = (Appointment) obj;
                if (this.day > appt.getDay())
                   return 1;
                else if (this.day < appt.getDay());
                return -1;
             return 0;
           public String toString() {
             StringBuffer buffer = new StringBuffer();
             buffer.append("Description: " + description);
             buffer.append(", Date: " + day + "/" +month+ "/" +year);
             buffer.append(", Start Time: " + startTime);
             buffer.append(", End Time: " + endTime);
             return buffer.toString();
           public void read(){
             System.out.print("Description : ");String descIn=keyboard.next();
             System.out.print("Day : ");int dayIn=keyboard.nextInt();
             System.out.print("Month : ");int monthIn=keyboard.nextInt();
             System.out.print("Year : ");int yearIn=keyboard.nextInt();
             System.out.print("Start Time : ");String startIn=keyboard.next();
             System.out.print("End Time : ");String endIn=keyboard.next();
             boolean goodInput = false;
             do{          
                try{
                   setDay(dayIn);
                   setMonth(monthIn);
                   setYear(yearIn);
                   goodInput = true;
                    catch(IllegalArgumentException e){
                      System.out.println("INVALID ARGUMENT PASSED FOR day or month or year");
                      System.out.println(e);
                      System.out.print("RE-ENTER VALID ARGUMENT FOR DAY : ");dayIn=keyboard.nextInt();
                      System.out.print("RE-ENTER VALID ARGUMENT FOR MONTH : ");monthIn=keyboard.nextInt();
                      System.out.print("RE-ENTER VALID ARGUMENT FOR YEAR : ");yearIn=keyboard.nextInt();                                        
             }while(!goodInput);
       }

    Array
    import java.util.*;
    class Array
         private Appointment[] app;
         private int nElems;
         Appointment tempApp;
         public Array(int max)
              app = new Appointment[max];
              nElems = 0;
         public Array(String desc, int day, int month, int year, String sTime, String eTime)
              app = new Appointment[100];
              nElems = 0;
       public int size()
          { return nElems; }
         void add(){
              Appointment appointmentToAdd = new Appointment();
              // Read its details
              appointmentToAdd.read();
              // And add it to the studentList
              //app[nElems].add(appointmentToAdd);
         public void add(String desc, int day, int month, int year, String sTime, String eTime)
            app[nElems] = new Appointment(desc, day, month, year, sTime, eTime);
            nElems++;             // increment size
              Appointment appointmentToAdd = new Appointment(desc, day, month, year, sTime, eTime);
              // And add it to the studentList
              //app[nElems].add(appointmentToAdd);
          public void insert(Appointment tempApp) {
        int j;
        for (j = 0; j < nElems; j++)
          // find where it goes
          if (app[j] > tempApp) // (linear search)
            break;
        for (int k = nElems; k > j; k--)
          // move bigger ones up
          app[k] = app[k - 1];
        app[j] = tempApp; // insert it
        nElems++; // increment size
       public void display()       // displays array contents
            for(int j=0; j<nElems; j++)    // for each element,
              app[j].display();     // display it
            System.out.println("");
         public void insertionSort()
       int in, out;
       for(out=1; out<nElems; out++) // out is dividing line
         Appointment temp = app[out];    // remove marked person
         in = out;          // start shifting at out
         while(in>0 &&        // until smaller one found,
            app[in-1].getMonth().compareTo(temp.getMonth())>0)
          app[in] = app[in-1];     // shift item to the right
          --in;          // go left one position
         app[in] = temp;        // insert marked item
         } // end for
       } // end insertionSort()
    }Menu
    import java.util.*;
    class Menu{
       private static Scanner keyboard = new Scanner(System.in);
       int option;
         Menu(){
            option=0;
         void display(){
              // Clear the screen
            System.out.println("\n1 Display");
              System.out.println("\n2 Insert");          
              System.out.println("3 Quit");          
         int readOption(){
            System.out.print("Enter Option [1|2|3] : ");
              option=keyboard.nextInt();
              return option;
    }Tester
       import java.util.*;
       import java.util.Arrays;
        class ObjectSortApp
           public static void main(String[] args)
                   int maxSize = 100;
                   Array arr;
                   arr = new Array(maxSize)
                   Appointment app1 = new Appointment("College Closed", 30, 4, 2009, "09:30", "05:30");;
                   Appointment app2 = new Appointment("Assignment Due", 25, 4, 2009, "09:30", "05:30");
             Appointment app3 = new Appointment("College Closed", 17, 4, 2009, "09:30", "05:30");
             Appointment app4 = new Appointment("Easter Break", 9, 4, 2009, "01:30", "05:30");
             Appointment app5 = new Appointment("College Opens", 15, 4, 2009, "09:30", "05:30");
             Appointment app6 = new Appointment("Assignment Due", 12, 4, 2009, "09:30", "05:30");
             Appointment app7 = new Appointment("Exams Begin", 11, 4, 2009, "09:30", "05:30");
                //To sort them we create an array which is passed to the Arrays.sort()
            //method.
            Appointment[] appArray = new Appointment[] {app1, app2, app3, app4, app5, app6, app7};
             System.out.println("Before sorting:");
            //Print out the unsorted array
            for (Appointment app : appArray)
                System.out.println(app.toString()); 
                Arrays.sort(appArray);
             //arr.insertionSort();      // insertion-sort them
             System.out.println("\n\nAfter sorting:");               
            //Print out the sorted array
            for (Appointment app : appArray)
                System.out.println(app.toString());
              Menu appMenu = new Menu();
              int chosenOption;
              do{
                 appMenu.display();
                   chosenOption=appMenu.readOption();
                   for (Appointment app : appArray)
                   switch(chosenOption){
                      case 1 : app.display(); break;
                        case 2 : arr.add(); break;
                        default:;
              }while(chosenOption != 3);    
          } // end main()
       } // end class ObjectSortApp

  • How to extend  breadth first Search for Binary Tree to any kind of Tree??

    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
    I have following code to successfully apply for breadth first Search in Binary Tree as follows,
    package a.border;
    import java.util.ArrayList;
    import java.util.LinkedList;
    public class Tree
        int root;
        Tree left;
        Tree right;
        static ArrayList<Integer> list = new ArrayList<Integer>();
        static ArrayList<Tree> treeList = new ArrayList<Tree>();
        private static LinkedList<Tree> queue = new LinkedList<Tree>();
         * @param root root value
         * @param left left node
         * @param right right node
        public Tree(int root, Tree left, Tree right)
            this.root = root;
            this.left = left;
            this.right = right;
        /** Creates a new instance of Tree
         * You really should know what this does...
         * @param root
        public Tree(int root)
            this.root = root;
            this.left = null;
            this.right = null;
         * Simply runs a basic left then right traversal.
        public void basicTraversal()
            //Check if we can go left
            if (left != null)
                left.basicTraversal();
            //Add the root
            list.add(root);
            //Check if we can go right
            if (right != null)
                right.basicTraversal();
        public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
            //Add the root to the arraylist, we know it is always the first entry.
            list.add(root);
            //Basically we add the first set of nodes into the queue for
            //traversing.
            //Query if left exists
            if (left != null)
                //Then add the node into the tree for traversing later
                queue.add(left);
            //Same for right
            if (right != null)
                queue.add(right);
            //Then we call the traverse method to do the rest of the work
            return traverse(list);
        private ArrayList<Integer> traverse(ArrayList<Integer> list)
            //Keep traversing until we run out of people
            while (!queue.isEmpty())
                Tree p = queue.remove();
                //Check if it has any subnodes
                if (p.left != null)
                    //Add the subnode to the back of the queue
                    queue.add(p.left);
                //Same for left
                if (p.right != null)
                    //Same here, no queue jumping!
                    queue.add(p.right);
                //Append to the ArrayList
                list.add(p.root);
            //And return
            return list;
         * Makes a tree and runs some operations
         * @param args
        public static void main(String[] args)
             *                             4
             *          t =           2       6
             *                      1   3    5   7
            Tree leaf6 = new Tree(1);
            Tree leaf7 = new Tree(3);
            Tree leaf8 = new Tree(5);
            Tree leaf9 = new Tree(7);
            Tree t4 = new Tree(2, leaf6, leaf7);
            Tree t5 = new Tree(6, leaf8, leaf9);
            Tree t = new Tree(4, t4, t5);
            t.basicTraversal();
            System.out.println("Here is basicTraversal ="+list.toString());
            list.clear();
            t.getBreadthTraversal(list);
            System.out.println("getBreadthTraversal= " +list.toString());
            list.clear();
        }Can Guru help how to update to any kind of tree??
    here this code is for the tree like:
             *                             4
             *          t =           2       6
             *                      1   3    5   7
             */But i hope the new code can handle tree like:
             *                             4
             *                           /   | \
             *                          /     |   \
             *          t =            2     8   6
             *                        / |  \    |    /| \
             *                      1 11  3 9   5 10  7
             */Thanks

    sunnymanman wrote:
    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
    What do all trees have in common? And what do all nodes in trees have in common?
    At least these things:
    interface Tree<T> {
        Node<T> getRoot();
    interface Node<T> {
        T getData();
        List<Node<T>> getChildren();
    }Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
    class BinaryTree<T extends Comparable<T>> implements Tree<T> {
        protected BTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class BTNode<T> implements Node<T> {
        private T data;
        private Node<T> left, right;
        public List<Node<T>> getChildren() {
            List<Node<T>> children = new ArrayList<Node<T>>();
            children.add(left);
            children.add(right);
            return children;
        public T getData() {
            return data;
    class NTree<T> implements Tree<T> {
        private NTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class NTNode<T> implements Node<T> {
        private T data;
        private List<Node<T>> children;
        public List<Node<T>> getChildren() {
            return children;
        public T getData() {
            return data;
    }Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
    interface Traverser<T> {
        List<Node<T>> traverse(T goal, Tree<T> tree);
    }And finally write an implementation for it:
    class BreathFirst<T> implements Traverser<T> {
        public List<Node<T>> traverse(T goal, Tree<T> tree) {
            Node<T> start = tree.getRoot();
            List<Node<T>> children = start.getChildren();
            // your algorithm here
            return null; // return your traversal
    }... which can be used to traverse any tree! Here's a small demo of how to use it:
    public class Test {
        public static void main(String[] args) {
            Tree<Integer> binTree = new BinaryTree<Integer>();
            // populate your binTree
            Tree<Integer> nTree = new NTree<Integer>();
            // populate your nTree
            Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
            // Look for integer 6 in binTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
            // Look for integer 6 in nTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
    }Good luck!

  • Pretty print of a binary tree

    Hi, I have to pretty print a binary tree composed of "key" values like 75, 70, 15, 2, etc. I have no idea how to create a dynamic method that can output a tree in the order that they are in. The tree is supposed to look like this:
                  15      
                  37
                       13
             75
                       90
                                 58
                             2
                  70
                       24The 15 is supposed to be in the top middle of the tree. Can anyone give me any help or hints to get started? Thanks.

    I guess you mean this
             15
      13              37
    2            24           75
                        58       90
                          70

  • Creating Insert Method for a binary tree

    I have code for a binary tree http://sourcepost.sytes.net/sourceview.aspx?source_id=5046
    I'm trying to create an insert method that will accept an element and insert it into my binary tree. The main purpose of this is to test my traversal functions, intrav(), postrav(), pretrav(). I have another class that will create 10 random numbers and call insert() to insert them into my tree. Can anyone help me write this method?

    anyone?

  • Writting Methods of Binary Tree

    I am using java code to write some binary tree methods.
    Got stuck in some of the following methods.
    Hopefully i can get some help here.
    Public int width(){
    // Return the maximun number of nodes in each level
    Public boolean checkIsFullTree(){
    // Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full)
    Public boolean checkIsCompleteTree(){
    // Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full and is filled from left to right)
    at last
    Public int internalPathLength(){
    // Return The sum of all internal nodes of the paths from the root of an extended binary tree to each node.
    other words, the sum of all depths of nodes.
    Looking forawad to see some replies. Chrees

    I have came up with some ideas.
    Public boolean checkIsFullTree(TreeNode t, int currentHeight ) {
    int maxHeight = height(); // Maximum height.
    int currentHeight=currentHeight;
    if (t == null){
    return false;
    if (t.left() ! = null){
    currentHeight++;
    checkIsFullTree(t.left(), currentHeight);
    if (t.right() ! = null){
    currentHeight++;
    checkIsFullTree(t.right(), currentHeight);
    if ( t.left() == null && t.right() == null){
    if (currentHeight == maxHeight) {
    check = true;
    }else{
    check = false;
    But i am missing sometime here i guess.
    }

  • When I try to print from my iPad I see a message "searching for printer" and then "no printer found.".  I have a printer application loaded and it finds my wireless printer.   How do I get the iPad to do the same so I can print from emails, the web, etc?

    When I try to print from my iPad I see a message "searching for printer" and then "no printer found.".  I have a printer application loaded and it finds my wireless printer.   How do I get the iPad to do the same so I can print from emails, the web, etc?  Thanks

    sandrafromsilver spring wrote:
    When I try to print from my iPad I see a message "searching for printer" and then "no printer found.".  I have a printer application loaded and it finds my wireless printer.   How do I get the iPad to do the same so I can print from emails, the web, etc?  Thanks
    Go to the following link:
    http://jaxov.com/2010/11/how-to-enable-airprint-service-on-mac-os-x-10-6-5/

Maybe you are looking for