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?

Similar Messages

  • How to create a method for reading a file

    i tried to make it as static method for reading a file and
    then to return string
    is this code correct?
              public static String fileMaterial(String fileName)
                   fileReader = new BufferedReader(new FileReader(fileName));
                   info = fileReader.readLine();
                   while(school != null)     {                    
                        return info;
                        info = fileReader.readLine();

    I created a class you might want to look at. I come from a world of C and love fgets() and other FILE stream functions. I created a class that uses the Java I/O buts to the calling application behaves like fgets and such. The block of code where I do the calling in the calling program even looks like C. In my class I capture almost all errors and set error buffers to the errors. The calling program looks at the return to see if it succedded or errored.
    BuffIO new = BuffIO.fopen("fiilename", "r");
    String s;
    if((s = new.fgets()) == null)
    System.err.println("error reading file: " + new.ferror());
    That would be waht the calling program does

  • What is wrong with my delete method in my binary tree

    code..okay so somehow everytime I delete a number that exist it says it has been deleted later when..I display the tree the node wasn' t really deleted at all here is the code..
         public boolean delete(int numbers)
              Node now = rootOrigin;
              Node ancestor = rootOrigin;
              boolean isLeftChild = true;
              if(find(numbers)!= null)
                   if((now.LeftChildOfMine == null)&&(now.RightChildOfMine == null))
                        if(now == rootOrigin)
                             rootOrigin = null;
                        else if(isLeftChild)
                             ancestor.LeftChildOfMine = null;
                        else
                             ancestor.RightChildOfMine = null;
                   else if((now.LeftChildOfMine != null)&&(now.RightChildOfMine == null))
                        if(now==rootOrigin)
                             now = now.LeftChildOfMine;
                        else if(isLeftChild)
                             ancestor.LeftChildOfMine = now.LeftChildOfMine;
                        else
                             ancestor.RightChildOfMine = now.LeftChildOfMine;
                   else if((now.LeftChildOfMine == null)&&(now.RightChildOfMine != null))
                        if(now==rootOrigin)
                             rootOrigin = now.RightChildOfMine;
                        else if(isLeftChild)
                             //ancestor.LeftChildOfMine = now.RightChildOfMine;
                             ancestor.RightChildOfMine = now.LeftChildOfMine;
                        else
                             //ancestor.RightChildOfMine = now.RightChildOfMine;
                             ancestor.LeftChildOfMine = now.RightChildOfMine;
                   else if((now.LeftChildOfMine != null)&&(now.RightChildOfMine != null))
                        //get successor of node to delete(current)
                        Node successor = getSuccessor(now);
                        //connect parent of current to successor instead
                        if (now == rootOrigin)
                             rootOrigin = successor;
                        else if(isLeftChild)
                             ancestor.LeftChildOfMine = successor;
                        else
                             ancestor.RightChildOfMine = successor; //connect successor to current's left child
                        successor.LeftChildOfMine = now.LeftChildOfMine;
              return true;     
              else
                   return false;
         }Also here is the method that finds the successor of the node that will replace the node that i want to delete
         private Node getSuccessor(Node delNode)
              Node successorParent = delNode;
              Node successor = delNode ;
              Node now = delNode.RightChildOfMine;
              while(now != null)
                   successorParent = successor;
                   successor = now;
                   now = now.LeftChildOfMine;
              if(successor != delNode.RightChildOfMine)
                   successorParent.LeftChildOfMine = successor.RightChildOfMine;
                   successor.RightChildOfMine = delNode.RightChildOfMine;
                   return successor;
         }Okay also a while ago when I focused on traversing(nodes kept displaying more than once) my prof. said the problem was in my insertion method.
    It mayber the insertion method's fault again
         public void insert(int numbers)
              Node newNode = new Node(numbers);
              if(rootOrigin == null)     
                   rootOrigin = newNode;     // newNode will be the root of the tree
              else
                   Node current = rootOrigin;
                   Node parent;
                   while(true)
                        parent = current;
                        if(numbers < current.numbers)
                             current = current.LeftChildOfMine;
                             if(current == null)
                                  parent.LeftChildOfMine = newNode;
                                  return;
                        else
                             current = current.RightChildOfMine;
                             if(current == null)
                                  parent.RightChildOfMine = newNode;
                                  return;
         }

    DaDonYordel wrote:
              if(find(numbers)!= null)
                   if((now.LeftChildOfMine == null)&&(now.RightChildOfMine == null))Shouldn't you be assigning the result of the find() to now?

  • A question on a build method in a Binary Tree Program

    So I'm working on making 20 Questions in java and I'm supposed to make a construct that calls a build method.
    I'll post my code as I have it so far.
    The game is supposed to work so that there's an original question and then if the user selects yes, then the answer goes to the left link. The no answer goes to the right link and then it keeps going yes for the left, no for the right.
    How do I call the build method recursively to do that?
    public class GameTree {
    * BinaryTreeNode inner class used to create new nodes in the GameTree.
    private class BinaryTreeNode {
    private String data;
    private BinaryTreeNode left;
    private BinaryTreeNode right;
    BinaryTreeNode(String theData) {
    data = theData;
    left = null;
    right = null;
    BinaryTreeNode(String theData, BinaryTreeNode leftLink, BinaryTreeNode rightLink) {
    data = theData;
    left = leftLink;
    right = rightLink;
    * instance variables.
    private BinaryTreeNode root;
    private Scanner my_inputFile;
    private String currentFileName;
    private BinaryTreeNode currentNodeReferenceInTree;
    * Constructor needed to create the game.
    * @param name
    * this is the name of the file we need to import the game questions
    * and answers from.
    public GameTree(String name) {
    // TODO: Complete this method
         currentFileName = name;
         try {
              my_inputFile = new Scanner(new File(currentFileName));
         catch (FileNotFoundException e) {
         root = build();
         my_inputFile.close();
    public BinaryTreeNode build() {
         String token2 = my_inputFile.nextLine();
         if(!isQuestion(token2))
              return new BinaryTreeNode(token2);
         else{
              BinaryTreeNode rightTreeSide = build();
              BinaryTreeNode leftTreeSide = build();
              return new BinaryTreeNode(token2,leftTreeSide, rightTreeSide);
    * Ask the game to update the current node by going left for Choice.yes or
    * right for Choice.no Example code: theGame.playerSelected(Choice.Yes);
    * @param yesOrNo
    public void playerSelected(Choice yesOrNo) {
         if(userSelection == Choice.No)
              currentNodeReferenceInTree = currentNodeReferenceInTree.right;
         if(userSelection == Choice.Yes)
              currentNodeReferenceInTree = currentNodeReferenceInTree.left;
    I have a separate .java that already says
    public enum Choice {
    Yes, No
    };

    When you post code, wrap it in code tags so it's legible. When you're inputting the text, highlight it, and then click the "CODE" button above the text input box. It can be almost impossible to read code that's not formatted like that.
    You ask "How do I call the build method recursively to do that?" You don't call recursive methods any differently than you call any other kind of method. Can you clarify what difficulty you're having?

  • Problem Creating a query for a hierarchical tree. [using connect by prior]

    Hi all,
    I have 2 tables.
    box (box_id, box_name)
    item(item_id, item_name, box_id)
    In a box there are several items.
    I want to create a hierachical tree to display items that are present in each box.
    LIKE:
    |---BOX1
    | |----ITEM 1
    | |----ITEM 2
    |
    |---BOX2
    | |----ITEM 1
    | |----ITEM 2
    Currently i am trying this query:
    SELECT -1 state, box_name, 'icon' icon, box_id val
    from box b, item i;
    I don't know what value to put for level, i don't know how to code the 'connect by prior' part.
    Could you please advise me?
    Michaël.
    PS. Then i will eventually use this query in forms builder.

    Note the name of this forum is "SQL Developer *(Not for general SQL/PLSQL questions)*" - so only for issues with the SQL Developer tool. Please post these questions under the dedicated SQL And PL/SQL forum.
    Regards,
    K.

  • I will pay, who creates a method for importing tables from MS word

    I need a script or any other type of method, which will import the MSword document, which have tables and footnotes.
    WIth "Place" option (with "SHift"), it only imports the first page of word document, and even that first page is degraded and some part of  footnotes are moved to the second page of Indesign.
    for example,see such document: http://d2.minus.com/1342790256/zDuntjI5q2iNIJqkk5UPJA/dbjwjsXzUbRmjD/sample.rtf
    i will pay him, who will do that job (offer me your bid).
    my info:
    mail: selnomeria(*)yahoo.com
    skype: oceane.sa

    Hello!
    First of all:
    Indesign does not support footnotes in tables. There are some tricks i use, for example making a "hidden footnote reference" somwhere in the page (just assign a 0.1pt size and fillcolor of "None") but it's just a ugly hack and if you have to reformat the tables you will have to rebuild all teh footnotes. move them around etc.
    Second:
    If one of the cells in the table you are importing is larger (verticaly) than the page size the autoflow will stop. The table is imported in the story (check it out in the story editor) but indesign cannot display it. Enlage the frame until the cell fits (or make the cell smaller -decrease the text size?) and reflow the rest of the text.
    Third:
    If you are working with large tables and especialy large cells be prepared to have numerous crashes. And i mean NUMEROUS!! Every time you try to change something in the table.
    i am sorry to be the bearer of bad news but at the moment table and footnote support in indesign is crappy at best, and i don't think there's anyone besides the guys form Adobe that can do anything to help you.

  • Is it possible to create findBy method for collection of ids?

    subj -
    I have a set of ids (HashSet of Integers).
    is it possible to create such findBy method which retrieves group of entity beans with ids specified in the set?

    You could do something like:
    PrimKeyBean
    public PrimKey ejbSelectPrimKey(Long key) throws FinderException;
    public Collection getPrimKeys(Collection keyset) {
      try{
        Vector output = new Vector();
        Iterator it = keyset.iterator();
        while(it.hasNext()){
          output.add(ejbSelectPrimKey((Long)it.Next()));
        return output;
      } catch (FinderException fe) {}
    ...deploymentdescriptor.ejb
    <query>
    <query-method>
    <method-name>ejbSelectPrimKey</method-name>
    </query-method>
    <ejb-ql>
    SELECT OBJECT(o) FROM pkTable o WHERE pkTablePK = ?1
    </ejb-ql>
    </query>
    ...client
    Collection c = primKey.getPrimKeys(keyset);
    ...

  • Createa a  method for creating dynamic queries

    Hi,
    I am trying to create a public method in a class to generate Dynamic SQL Queries.The method has 4 parameters :
    WHERESTRING TYPE STRING
    FROMTABLE TYPE STRING
    SELECTFIELDS TYPE STRING
    INTOTABLE TYPE ANY TABLE
    the process is :
    SELECT (selectfields) FROM (fromtable) INTO <INTOTABLE> WHERE (wherestring).
    However I get error in the INTOTABLE, it does not recognize the parameter. What am I doing wrong ?

    Resolved myself!

  • Getting the height of a binary tree

    So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
    I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
    public int getHeight()
              int height;
              height = getHeightRecur(root);
              return height;
         public int getHeightRecur(BinTreeNode node)
              int theight;
              if(node == null)
                   theight = 0;
              else
                   theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
              return theight;
         private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              if(y>x)
                   result = y;
              return result;
         }

    j2ee_ubuntu wrote:
    it may help at some extent..
    private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              else if(y>x)
                   result = y;
    else //when both are equal
    result =x; OR result = y;//You can use one of them
              return result;
         }Edited by: j2ee_ubuntu on Nov 6, 2008 12:30 AMWhy not just use [ Math.max|http://java.sun.com/javase/6/docs/api/java/lang/Math.html#max(int,%20int)] or write
    public static int max(int a, int b) {
        return (a >= b) ? a : b;
    }

  • Creating non binary trees in Java

    Hi everybody actually i am used in creating binary trees in java,can u please tell me how do we create non binary -trees in java.

    Hi,
    Can u let us know the application area for Non binary tree.
    S Rudra

  • Binary Tree    (insert level by level)

    Hello,
    I'm trying to program a binary tree. It's totally clear for me to insert new (Integer) Values in an ordinary binary tree.
    I simply have to check if the root is equal (--> ready) smaller or larger than the value. I repeat this until I reached a leaf and then I insert a new node.
    BUT:
    My teacher gave me following problem: Inserting values level by level. The first element is the root, the leftson of the root is nuber2 the rightson of the root is number3
    The leftson of root's leftson is number4, the rightson of root's leftson is number 5, the leftson of root's rightson is number 6 and so on.
    I have NO idea how to program that.
    For example: the 23rd element is in the tree: left, right, right, right, whilst the 24th element is right, left, left, left.
    I cannot find a recursive structure, that solves the problem.
    Perhaps YOU can save me from gettin' mad ;o)
    I really hope so.

    It's not quite clear what you mean by level-by-level (at least not to me). The structure of a binary tree depends in the insert order. If you insert 1,5,2,8 the tree will look different to when you insert 1,2,3,4. In the last case the tree actually has degenerated to a linked list (there are only rightsons).
    Now, to minimize the number of levels (if that's what this is about) there's a technique called balancing. In a perfectly balanced binary tree each level is filled before a new level is started. This is quite complicated. Search the net or look in some data structures textbook for balanced binary trees.

  • Succinct encoding for binary tree with n nodes...

    How do I find all possible bit strings (Succinct encoding) for a binary tree with order n? Can anybody give me an algorithm?

    I associate the order of a tree with some sort of a search or traversal. What do you mean by a "+tree with order n+"?
    Could you perhaps give an example of what you're looking for?

  • Try to create a method to return an object as xml

    I'm trying to create a method for an object to return the objects attributes in xml format.
    here is what I have done so far:
    -- create the object hierachy
    create or replace type ras4.atomic_tp as object
         (atomic_instance_id     varchar2(8),
         service_instance_id     varchar2(8),
         parent_atomic_instance_id varchar2(8),
         MEMBER FUNCTION return_xml RETURN varchar2)
    NOT INSTANTIABLE
    NOT FINAL;
    create or replace type ras4.parm_const_tp under ras4.atomic_tp
         (parameter_name          varchar2(75))
    NOT INSTANTIABLE
    NOT FINAL;
    create or replace type ras4.contact_tp under ras4.atomic_tp
         (address_line_1          varchar2(80),
         address_line_2          varchar2(80),
         address_line_3          varchar2(80),
         city               varchar2(20),
         state               varchar2(2),
         country               varchar2(20),
         postal_code          varchar2(20),
         voice_telephone          varchar2(20),
         dns_telephone          varchar2(20),
         fax               varchar2(20),
         email               varchar2(80),
         url               varchar2(20),
         contact_inst          varchar2(255))
    NOT INSTANTIABLE
    NOT FINAL;
    create or replace type PERSON_tp under contact_tp
         (prefix               varchar2(7),
         first_name          varchar2(50),
         middle_name          varchar2(50),
         last_name          varchar2(50),
         suffix               varchar2(20),
         nick_name          varchar2(50),
    OVERRIDING MEMBER FUNCTION return_xml return varchar2)
    INSTANTIABLE
    FINAL;
    create table ras4.person_tb of ras4.person_tp;
    insert into ras4.person_tb values
    (ras4.person_tp('00001', '00001', '00001', '1111 Trail Lake Dr.', null, null, 'Fort Worth',
    'TX', 'USA', '76233', '(817)346-0004', null, null, '[email protected]', 'www.tom.com', 'no calls after 10:00 please',
    'Mr.', 'Tom', 'Scott', 'Tiegen', null, 'Tom'));
    commit;
    -- now different things I have tried to get the member function to work:
    CREATE or replace TYPE BODY RAS4.PERSON_TP AS
         overriding MEMBER FUNCTION RETURN_XML RETURN VARCHAR2 IS
    qryCtx DBMS_XMLGEN.CTXHANDLE;
    result CLOB;
    BEGIN
         qryCtx :=
         DBMS_XMLGEN.NEWCONTEXT ('select self.first_name from dual;');
    result := DBMS_XMLGEN.GETXML(qryCtx);
              RETURN (RESULT);
         END;
    END;
    I try to invoke the method as below:
    DECLARE
    v_person ras4.person_tp;
    v_person_ref ref ras4.person_tp;
    V_string varchar2(2000);
    BEGIN
    select value(a)
    into v_person
    from ras4.person_tb a
    where a.atomic_instance_id = '00001';
    v_string := v_person.return_xml;
    DBMS_OUTPUT.PUT_LINE(v_string);
    END;
    I get the following error:
    DECLARE
    ERROR at line 1:
    ORA-19206: Invalid value for query or REF CURSOR parameter
    ORA-06512: at "SYS.DBMS_XMLGEN", line 83
    ORA-06512: at "RAS4.PERSON_TP", line 7
    ORA-06512: at line 12
    -- I try to use
    from the command line I type in this:
    select sys_xmlgen(value(p))
    from person_tb p
    where p.atomic_Instance_id = '00001';
    and it seems to work.
    trying to put this into a member function - I try this:
    CREATE or replace TYPE BODY RAS4.PERSON_TP AS
         overriding MEMBER FUNCTION RETURN_XML RETURN VARCHAR2 IS
    v_string varchar2(200);
    v_person ras4.person_tp;
    BEGIN
         v_person := self;
         select v_person.first_name into v_string from dual;
         return (select sys_xmlgen(value(v_person)));
         END;
    END;
    This fails to compile.
    any help is greatly appreciated.
    tom

    PN,
    First, it's impossible to create static method with WD IDE designers for controllers.
    Next, if you simply need to call method from wdDoModifyView, just create instance method createHTMLViewer in regular way then call it from wdDoModifyView via wdThis.createHTMLViewer().
    Third, you may create this method manually directly in source code, just place it at the end of controller between comments //@begin other ... //@end.
    Valery Silaev
    EPAM Systems
    http://www.NetWeaverTeam.com

  • Syntax error when creating Overwrite method - implicit enhancement

    Hi,
    I am working at a customer site, and need to implicitly enhance certain methods. I would like to create an Overwrite Method for the following class/method:
    CL_CRM_MKTDEF_DEFAULTS_PERSIST -> HEADER_WITH_KEY_EXITS_IN_DBASE( )
    I proceeded in the following way:
    Open class CL_CRM_MKTDEF_DEFAULTS_PERSIST in class builder (SE24)
    Select menu path Class -> Enhance
    Create, or select, enhancement implementation ZCRM_MKTDEF_PRD
    Select method HEADER_WITH_KEY_EXITS_IN_DBASE, select menu path Edit -> Enhancement Operation -> Add Overwrite Method
    Click on u201CNavigation to Overwrite Exitu201D
    After navigating to the Overwrite Exit, I click on "Check" to perform a syntax check (notice, I have not yet implemented any code. Everything so far has been done by the wizard).
    Now, I get the following error:
    Enhancement Implementation ZCRM_MKTDEF_PRD
    Unable to interpret "IS_DEFAULTS_ATTR". Possible causes: Incorrect
    spelling or grammar.
    When I create Overwrite methods for any other method in the same class, the same error does NOT occur. As far as I can tell, there is nothing special about this method that should cause this error.
    I would greately appreciate any help that any of you could give me on this one.
    thank you and best regards,
    - Marius
    PS: Here is my code (which was generated after I followed the outlined steps above) for your reference:
    CLASS LCL_ZCRM_MKTDEF_PRD DEFINITION.
    PUBLIC SECTION.
    CLASS-DATA OBJ TYPE REF TO LCL_ZCRM_MKTDEF_PRD.
    DATA CORE_OBJECT TYPE REF TO CL_CRM_MKTDEF_DEFAULTS_PERSIST .
    INTERFACES  IOW_ZCRM_MKTDEF_PRD.
      METHODS:
       CONSTRUCTOR IMPORTING CORE_OBJECT
         TYPE REF TO CL_CRM_MKTDEF_DEFAULTS_PERSIST OPTIONAL.
    ENDCLASS.
    CLASS LCL_ZCRM_MKTDEF_PRD IMPLEMENTATION.
    METHOD CONSTRUCTOR.
      ME->CORE_OBJECT = CORE_OBJECT.
    ENDMETHOD.
    METHOD IOW_ZCRM_MKTDEF_PRD~HEADER_WITH_KEY_EXITS_IN_DBASE.
    *" Declaration of Overwrite-method, do not insert any comments here please!
    *"methods HEADER_WITH_KEY_EXITS_IN_DBASE
    *"  importing
    *"    !IS_DEFAULTS_ATTR type CRMS_MKTDEF_DEFAULTS_DATA
    *"  returning
    *"    value(EV_EXISTS) type CRMT_BOOLEAN
    *"  exceptions
    *"    FAILURE .
    ENDMETHOD.
    ENDCLASS.

    Note 1256889

  • MorseCode Binary Tree

    So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
    For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
    I am sorry for such sloppy code.. I have been changing and rearranging too much.
    import java.io.*;
    import java.util.*;
    public class MorseCode extends BinaryTree{
         static BufferedReader in;
         static BinaryTree<String> bT = new BinaryTree<String>();
    /*     public static void loadTree() throws FileNotFoundException, IOException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
         public static String decode(Character c) throws IOException{
              if(c.equals("null")){
                   return "";
              }else if(c.equals(" ")){
                   return " ";
              }else{
                   return (":" + find(c));
         public static String find(Character c) throws IOException, FileNotFoundException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
              Queue<BinaryTree> data = new LinkedList<BinaryTree>();
              BinaryTree<String> tempTree = bT;
              String temp = null;
              Character tempChar = null;
              data.offer(tempTree);
              while(!data.isEmpty()){
                   tempTree = data.poll();
                   temp = tempTree.getData();
                   tempChar = temp.charAt(0);
                   if(tempChar.equals(c)){
                        break;
                   data.offer(tempTree.getRightSubtree());
                   data.offer(tempTree.getLeftSubtree());
              return temp.substring(2);               
         public static void main(String[] args) throws FileNotFoundException, IOException{
              Scanner scan = new Scanner(new FileReader("encode.in.txt"));
              String s = "";
              String temp = "";
              while(scan.hasNextLine()){
                    temp = scan.nextLine();
                    for(int i = 0; i < temp.length(); i++){
                         s = s + decode(temp.charAt(i));
              System.out.println(s);
    /** Class for a binary tree that stores type E objects.
    *   @author Koffman and Wolfgang
    class BinaryTree <E> implements Serializable
      //===================================================
      /** Class to encapsulate a tree node. */
      protected static class Node <E> implements Serializable
        // Data Fields
        /** The information stored in this node. */
        protected E data;
        /** Reference to the left child. */
        protected Node <E> left;
        /** Reference to the right child. */
        protected Node <E> right;
        // Constructors
        /** Construct a node with given data and no children.
            @param data The data to store in this node
        public Node(E data) {
          this.data = data;
          left = null;
          right = null;
        // Methods
        /** Return a string representation of the node.
            @return A string representation of the data fields
        public String toString() {
          return data.toString();
      }//end inner class Node
      //===================================================
      // Data Field
      /** The root of the binary tree */
      protected Node <E> root;
      public BinaryTree()
        root = null;
      protected BinaryTree(Node <E> root)
        this.root = root;
      /** Constructs a new binary tree with data in its root,leftTree
          as its left subtree and rightTree as its right subtree.
      public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
        root = new Node <E> (data);
        if (leftTree != null) {
          root.left = leftTree.root;
        else {
          root.left = null;
        if (rightTree != null) {
          root.right = rightTree.root;
        else {
          root.right = null;
      /** Return the left subtree.
          @return The left subtree or null if either the root or
          the left subtree is null
      public BinaryTree <E> getLeftSubtree() {
        if (root != null && root.left != null) {
          return new BinaryTree <E> (root.left);
        else {
          return null;
      /** Return the right sub-tree
            @return the right sub-tree or
            null if either the root or the
            right subtree is null.
        public BinaryTree<E> getRightSubtree() {
            if (root != null && root.right != null) {
                return new BinaryTree<E>(root.right);
            } else {
                return null;
         public String getData(){
              if(root.data == null){
                   return "null";
              }else{
                   return (String) root.data;
      /** Determine whether this tree is a leaf.
          @return true if the root has no children
      public boolean isLeaf() {
        return (root.left == null && root.right == null);
      public String toString() {
        StringBuilder sb = new StringBuilder();
        preOrderTraverse(root, 1, sb);
        return sb.toString();
      /** Perform a preorder traversal.
          @param node The local root
          @param depth The depth
          @param sb The string buffer to save the output
      private void preOrderTraverse(Node <E> node, int depth,
                                    StringBuilder sb) {
        for (int i = 1; i < depth; i++) {
          sb.append("  ");
        if (node == null) {
          sb.append("null\n");
        else {
          sb.append(node.toString());
          sb.append("\n");
          preOrderTraverse(node.left, depth + 1, sb);
          preOrderTraverse(node.right, depth + 1, sb);
      /** Method to read a binary tree.
          pre: The input consists of a preorder traversal
               of the binary tree. The line "null" indicates a null tree.
          @param bR The input file
          @return The binary tree
          @throws IOException If there is an input error
      public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
        // Read a line and trim leading and trailing spaces.
        String data = bR.readLine().trim();
        if (data.equals("null")) {
          return null;
        else {
          BinaryTree < String > leftTree = readBinaryTree(bR);
          BinaryTree < String > rightTree = readBinaryTree(bR);
          return new BinaryTree < String > (data, leftTree, rightTree);
      }//readBinaryTree()
      /*Method to determine the height of a binary tree
        pre: The line "null" indicates a null tree.
          @param T The binary tree
          @return The height as integer
      public static int height(BinaryTree T){
            if(T == null){
               return 0;
          }else{
               return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
      public static String preOrderTraversal(BinaryTree<String> T){
          String s = T.toString();
          String s2 = "";
          String temp = "";
          Scanner scan = new Scanner(s);
          while(scan.hasNextLine()){
               temp = scan.nextLine().trim();
               if(temp.equals("null")){
                   s2 = s2;
              }else{
                   s2 = s2 + " " + temp;
          return s2;
    }//class BinaryTree

    As well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
    public static void main(String[] args) throws FileNotFoundException, IOException{
        //Scanner scan = new Scanner(new FileReader("encode.in.txt"));
        Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
    public static String decode(Character c) throws IOException{
        if(c.equals("null")){
    c is a Character so it will never be the case that it is equal to the string n-u-l-l.
    Perhaps the behaviour of each of these methods needs to be (documented and) tested.

Maybe you are looking for

  • HP LaserJet Enterprise 500 color MFP M575 control panel display

    HP LaserJet 500 color MFP M575  have no Display. and is not anymore possible access any function. What is the problem behind that ?How can we solve this issue ? is it the problem with the control panel display or the logic board ? there is no dim mem

  • IPC Pricing routine for Product Family Margin in Quotation is not working

    Hi, I am working on the IPC Pricing Routine to calculate Item's Product Family Margin in the Quotation.  Process followed: Step 1:  Created a Group condition ZPFM for Product Family Margin and assigned to the pricing procedure.  Step 2:  Created a Va

  • Ipod 160 GB, why 148 GB

    Hi! I have 160 Gb ipod but when I connect to my pc they said 148 Gb even in my ipod said too, what happen with the rest 12 GB, I know they using some for the ipod but I know it's no more then 1 Gb but what happen with the rest 11 Gb lost or this ipod

  • SCOM 2012 Network Monitoring Does Not Show Servers

    We are testing out the network monitoring piece in SCOM 2012 but for some reason it never does show the servers.  We have a test switch with a monitored server connected directly to it but after the discovery completes it doesn't show the server as b

  • Window title bar?

    Hi all, Does anybody know how to set the window title bar like the one used by window.MessageDialog e.g. without the small icon image at the left corner? If I set the window.IsToolWindow attribute to TRUE, the small icon image is not displayed but th