Binary tree problems.

hi everyone.
I have an assignment to use a binary search tree whose nodes hold a reference to a string, and also to an int which is the count of how many times that word occurs in an input file, then it traverses the tree and prints out the result to an output file.
But when I compile, I get this one error, which I'm not sure how to fix.
the error says:
WordCount2.java:142: displayNode(java.lang.String,int) in Node cannot be applied to () localRoot.displayNode();
and here's he code:
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.lang.String.*;
class WordCount2
public static void main (String [] args) throws IOException
StringTokenizer tokenizer;
String inputpath, outputpath;
String line = "";
String str = "";
Tree tree = new Tree();
int i = 0;
int count = 0;
Node now = new Node();
BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the pathname of the input file: ");
inputpath = stdin.readLine();
System.out.println("Enter the pathname of the output file: ");
outputpath = stdin.readLine();
FileReader textFile1 = new FileReader(inputpath);
BufferedReader inputFile = new BufferedReader (textFile1);
FileWriter textFile2 = new FileWriter(outputpath);
PrintWriter outputFile = new PrintWriter(textFile2);
while ((line = inputFile.readLine()) != null)
tokenizer = new StringTokenizer(line, " ");
while (tokenizer.hasMoreTokens())
String s = tokenizer.nextToken().toLowerCase();
tree.insert(s, i);
tree.inOrderTraverse(now);
class Node
public String sData;
public int iData;
public Node leftChild;
public Node rightChild;
public Node()
sData = "";
iData = 0;
public void displayNode(String s, int i) throws IOException
String file = "test1.txt";
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader(fr);
String line = inFile.readLine();
String file2 = "outfile.txt";
FileWriter fw = new FileWriter (file2);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.print (s);
outFile.print (" - ");
outFile.print (i);
outFile.flush();
class Tree
private Node root;
public Tree()
root = null;
public void insert(String sd, int id)
Node newNode = new Node();
newNode.sData = sd;
newNode.iData = id;
if (root == null)
root = newNode;
else
Node current = root;
Node parent;
while (true)
parent = current;
if ((newNode.sData).compareTo(current.sData) < 0)
current = current.leftChild;
if (current == null)
parent.leftChild = newNode;
return;
else if((newNode.sData).compareTo(current.sData) == 0)
increment(newNode.iData);
else
current = current.rightChild;
if(current == null)
parent.rightChild = newNode;
return;
public void inOrderTraverse (Node localRoot)
if (localRoot != null)
inOrderTraverse(localRoot.leftChild);
localRoot.displayNode();
inOrderTraverse(localRoot.rightChild);
private int increment(int i)
return i++;
any help is greatly appreciated! thanks!

ok, thanks a lot!
so i was able to fix that, and it compiles, but when I run it, it gets stuck after i enter the name of the input and output files. anyone have any idea why it's doing that? I can't figure it out...
here's the edited code:
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.lang.String.*;
class WordCount2
public static void main (String [] args) throws IOException
StringTokenizer tokenizer;
String inputpath, outputpath;
String line = "";
String str = "";
Tree tree = new Tree();
int i = 0;
int count = 0;
Node now = new Node();
BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the pathname of the input file: ");
inputpath = stdin.readLine();
System.out.println("Enter the pathname of the output file: ");
outputpath = stdin.readLine();
FileReader textFile1 = new FileReader(inputpath);
BufferedReader inputFile = new BufferedReader (textFile1);
FileWriter textFile2 = new FileWriter(outputpath);
PrintWriter outputFile = new PrintWriter(textFile2);
while ((line = inputFile.readLine()) != null)
tokenizer = new StringTokenizer(line, " ");
while (tokenizer.hasMoreTokens())
String s = tokenizer.nextToken().toLowerCase();
tree.insert(s, i);
tree.inOrderTraverse(now);
class Node
public String sData;
public int iData;
public Node leftChild;
public Node rightChild;
public Node()
sData = "";
iData = 0;
public void displayNode(String s, int i) throws IOException
String file = "test1.txt";
FileReader fr = new FileReader (file);
BufferedReader inFile = new BufferedReader(fr);
String line = inFile.readLine();
String file2 = "outfile.txt";
FileWriter fw = new FileWriter (file2);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.print (s);
outFile.print (" - ");
outFile.print (i);
outFile.flush();
class Tree
private Node root;
public Tree()
root = null;
public void insert(String sd, int id)
Node newNode = new Node();
newNode.sData = sd;
newNode.iData = id;
if (root == null)
root = newNode;
else
Node current = root;
Node parent;
while (true)
parent = current;
if ((newNode.sData).compareTo(current.sData) < 0)
current = current.leftChild;
if (current == null)
parent.leftChild = newNode;
return;
else if((newNode.sData).compareTo(current.sData) == 0)
increment(newNode.iData);
else
current = current.rightChild;
if(current == null)
parent.rightChild = newNode;
return;
public void inOrderTraverse (Node localRoot) throws IOException
String s = "";
int i = 0;
if (localRoot != null)
inOrderTraverse(localRoot.leftChild);
localRoot.displayNode(s, i);
inOrderTraverse(localRoot.rightChild);
private int increment(int i)
return i++;
thanks again!

Similar Messages

  • Binary Tree Problem, help !!!!!!!

    Hi I have some Tree Traversal problem,
    my output has this problem,what's going on????
    Exception in thread "main" java.lang.NullPointerException
    at Tree.inTraversal2(Tree.java:150)
    at TreeTest.main(TreeTest.java:33)
    My Tree.java:
    class TreeNode {
       TreeNode leftNode;          
       TreeNode rightNode;
       int data;
       public TreeNode(int nodeData)
          data = nodeData;             
          leftNode = rightNode = null;
       public void insert(int value)
          if( value < data )
             if( leftNode == null )
                leftNode = new TreeNode(value);
             else
                leftNode.insert(value);
          else if ( value > data )
             if( rightNode == null )
                rightNode = new TreeNode(value);
             else
                rightNode.insert(value);
       }  //end method insert
    }  //end class TreeNode
    public class Tree {
       TreeNode root;
       Stack s;
       public Tree()
          root = null;
       public void insertNode(int value)
          if( root == null )
             root = new TreeNode(value);
          else
             root.insert(value);
       public void inTraversal2(TreeNode node)
             if( node == null )
             return;
         TreeNode p;
         p = node;
         do
                while(p != null)
                     s.push(p); //problem comes in here
                     p = p.leftNode;
                 if(!s.empty())
                     p = s.pop();
                     System.out.print( p.data + " " );
                     p = p.rightNode;
                   }while( (p != null) || (!s.empty()));
    }  //end class TreeMy Stack.java:
    public class Stack {
          TreeNode items[];
         int StackSize;
         int top;
        public Stack(int size)
             StackSize = size;
            items = new TreeNode[size];
            top = -1;
        public boolean empty()
             if(top == -1)
               return true;
            else
              return false;
        public boolean full()
             if(top == StackSize-1)
               return true;
             else
               return false;
        public void push(TreeNode c)
            if(full() == true)
               System.out.println("stack overflow");
            else
                items[++top] = c;
        public TreeNode pop()
             if(empty())
               System.out.println("stack underflow");
            return items[top--];
    }

    You don't seem to instantiate Stack anywhere.

  • Problem with binary tree please help

    i am trying to make a binary tree but the problem is that when i print the data only the last value is printed i think i am moving my root. but dont know how to solve it please help me.
    public void insert(String n)
    //          (void)
              if (root == null)
                   System.out.println("Root is null");
                   TreeNode temp = new TreeNode(n);
                   System.out.println("\n\n\n\n"+temp.name+"\n\n\n\n\n");
                   root = rootTemp = temp;
              else
                   System.out.println("Root is not null" +rootTemp.name);
                   insert(rootTemp, n);
         private TreeNode insert(TreeNode v, String n) {
              if (v == null)
                   return new TreeNode(n);
              else
                   if (n.compareTo(v.name) < 0)
                        v.left = insert(v.left, n);
                   else
                        v.right = insert(v.right, n);
                   return v;
         }

    Are you sure the problem is not in the printing code?
    I can't see any obvious mistakes after a quick look... But if "root" is a reference to the root node, what is "rootTemp"?

  • 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.
    :)

  • Binary Tree Help

    I have a project where I need to build a binary tree with random floats and count the comparisons made. The problem I'm having is I'm not sure where to place the comaprison count in my code. Here's where I have it:
    public void insert(float idata)
              Node newNode = new Node();
              newNode.data = idata;
              if(root==null)
                   root = newNode;
              else
                   Node current = root;
                   Node parent;
                   while(true)
                        parent = current;
                        if(idata < current.data)
                             comp++;
                             current = current.leftc;
                             if(current == null)
                                  parent.leftc = newNode;
                                  return;
                        else
                             current = current.rightc;
                             if(current == null)
                                  parent.rightc = newNode;
                                  return;
         }//end insertDo I have it in the right place? Also, if I'm building the tree for 10,000 numbers would I get a new count for each level or would I get one count for comparisons?? I'd appreciate anyone's help on this.

    You never reset the comp variable, so each timeyou
    insert into the tree, it adds the number ofinserts
    to the previous value.Yes, or something like that. I'm not sure what theOP
    really means.Yeah, it's hard to be sure without seeing the rest of
    the code.Sorry, I thought I had already posted my code for you to look at.
    Here's a copy of it:
    class Node
         public float data;
         public Node leftc;
         public Node rightc;
    public class Btree
         private Node root;
         private int comp;
         public Btree(int value)
              root = null;
         public void insert(float idata)
              Node newNode = new Node();
              newNode.data = idata;
              if(root==null)
                   root = newNode;
              else
                   Node current = root;
                   Node parent;
                   while(true)
                        parent = current;
                        comp++;
                        if(idata < current.data)
                             current = current.leftc;
                             if(current == null)
                                  parent.leftc = newNode;
                                  return;
                        else
                             current = current.rightc;
                             if(current == null)
                                  parent.rightc = newNode;
                                  return;
         }//end insert
        public void display()
             //System.out.print();
             System.out.println("");     
             System.out.println(comp);
    } //end Btree
    class BtreeApp
         public static void main(String[] args)
              int value = 10000;
              Btree theTree = new Btree(value);
              for(int j=0; j<value; j++)
                   float n = (int) (java.lang.Math.random() *99);
                   theTree.insert(n);
                   theTree.display();
    }

  • 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.

  • Binary tree - counting nodes

    i have got a binary tree and i need to write a method which can count the number of leaves.
    i have written the code as
    static int countLeaves(BinaryNode node) {
            if (node == null) {
                return 0;
            else if (node.left == null && node.right == null) {
                return 1;
            return countLeaves(node.left) + countLeaves(node.right);
    }but, how can i put the method in the main funcion, i have tried
    int leafCount = countLeaves(root);it gives an error message "non-static variable root cannot be referenced from a static context". How can i solve this problem? Thank you.

    the code looks like:
    public class BinaryTree<AnyType>
        public BinaryTree( )
            root = null;
        public BinaryTree( AnyType rootItem )
            root = new BinaryNode<AnyType>( rootItem, null, null );
        public void printPreOrder( )
            if( root != null )
                root.printPreOrder( );
        public void printInOrder( )
            if( root != null )
               root.printInOrder( );
        public void printPostOrder( )
            if( root != null )
               root.printPostOrder( );
        public void makeEmpty( )
            root = null;
        public boolean isEmpty( )
            return root == null;
        public void merge( AnyType rootItem, BinaryTree<AnyType> t1, BinaryTree<AnyType> t2 )
            if( t1.root == t2.root && t1.root != null )
                System.err.println( "leftTree==rightTree; merge aborted" );
                return;
            if( this != t1 )
                t1.root = null;
            if( this != t2 )
                t2.root = null;
        public BinaryNode<AnyType> getRoot( )
            return root;
        private BinaryNode<AnyType> root;
        static int countLeaves(BinaryNode node) {
            if (node == null) {
                return 0;
            else if (node.left == null && node.right == null) {
                return 1;
            return countLeaves(node.left) + countLeaves(node.right);
        static public void main( String [ ] args )
            BinaryTree<Integer> t1 = new BinaryTree<Integer>( 1 );
            BinaryTree<Integer> t3 = new BinaryTree<Integer>( 3 );
            BinaryTree<Integer> t5 = new BinaryTree<Integer>( 5 );
            BinaryTree<Integer> t7 = new BinaryTree<Integer>( 7 );
            BinaryTree<Integer> t2 = new BinaryTree<Integer>( );
            BinaryTree<Integer> t4 = new BinaryTree<Integer>( );
            BinaryTree<Integer> t6 = new BinaryTree<Integer>( );
            t2.merge( 2, t1, t3 );
            t6.merge( 6, t5, t7 );
            t4.merge( 4, t2, t6 );
            // i want to run the method countLeaves here
            int leafCount = countLeaves(root);
            System.out.println("Number of leaves: "+leafCount);
    }

  • How to remember the path while traverse a binary tree?

    Hi, again, I have difficulty handling tree search problems.
    The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
    I think the signature should be:
    // The path contains only 0s and 1s. 0 means go left and 1 means go right.
    public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
    // the class Node only has two fields:
    Node{
    Node left;
    Node right;
    I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
    I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
    Anyone wants to help?

    Hi, JosAh,
    That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
    The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
    So I changed your code to be:
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    return search(root.right, node, path);
    }I simply tested it with
    Stack<Integer> path = new Stack<Integer>();
    System.out.println( root, root.right.right, path);
    root is the root of a complete binary tree with 7 nodes(4 leaves).
    Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
    Considerring , the right branch never pops, I changed it into
    Then I changed it to :
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right ) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    if (search(root.right, node, path) != null) return path;
    path.pop();
    return path;
    With the same test case, it returns [].
    I will keep working on it.
    Cheers,
    Message was edited by:
    since81
    Message was edited by:
    since81

  • Putting words from a text file into a binary tree.

    I am having problems figuring out how to do this.
    the text file will have a sentence like this
    Every one likes to play games.
    My Dog tore up my apartment last night.
    How old are you sir.I know how to put regular strings into a binary tree, but I don't know what to do in order to put these textfile strings into it.
    I thought of using string tokenizer but I couldn't get that to work because the sentences are not a specific length, they can be any length. Can somebody give me some tips on what to use?
    Thank you

    JulianJ wrote:
    That will work?I'm sorry to tell you, that is a really bad question. Of course it won't work, because you did something else wrong. I have no idea what, but it's pretty certain that you haven't got everything right yet. (And that's nothing personal, it's just an observation about computer programming in general.) But don't let that stop you. And don't wait around for people to validate your ideas. Try it and see what happens. You won't break anything. And when it doesn't work, figure out why and carry on.

  • 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;
    }

  • How to serialize a binary tree object

    HI Friends,
    This is the problem.............................
    I got a binary Tree Program with root (object ) containing the elements in the tree.
    I got a server which performs insertions and deletions in the root.
    Once it has got the operations right it has to send this object to client and Client will perform the search over this Binary Tree.
    How to do this................................ Any Idea
    Anyone can get me the Code....... It will be great to u....
    reply me in this Id : [email protected]

    Have you looked at the TreeSet code.
    This is a collection which stores data as a binary tree. It is serializable, has a look at the readObject and writeObject methods.

  • Help loading a binary tree from file

    Hi all,
    So I am working on making a 20 question game using a binary tree. I have set it up so each time the user plays, if the computer cannot guess what they are thinking of, they tell the computer and it saves it. I am saving the tree in a text file recursively, in a format that looks something like this:
    Do you use it outside?
    a shovel
    [null]
    [null]
    is it round?
    a ball
    [null]
    [null]
    a TV
    [null]
    [null]
    The problem is now, I am having a very hard time rebuilding the tree when the user restarts the game. As you can see, the "{" indicates the beginning of a path and the "}" is the end. Can someone suggest a nice way to load this back up into my data structure? Thanks!!

    Cross-post here: [http://www.java-forums.org/java-2d/14237-help-loading-binary-tree-file.html]
    Recommended looking into XML

  • Deep cloning a Binary Tree

    Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
    public Object clone()
           DigitalTree<E> treeClone = null;
           try
               treeClone = (DigitalTree<E>)super.clone();
           catch(CloneNotSupportedException e)
               throw new Error(e.toString());
           cloneNodes(treeClone, this.root, treeClone.root);
           return treeClone;
       private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
           if(treeClone.size == 0)
               cloneNode = null;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
           else if(currentNode != null)
               cloneNode = (Node<E>)currentNode.clone();
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
       }In the Node class:
    public Object clone()
              Node<E> nodeClone = null;
              try
                   nodeClone = (Node<E>)super.clone();
              catch(CloneNotSupportedException e)
                   throw new Error(e.toString());
              return nodeClone;
           }

    Hello jssutton
    Your question inspired me to try my own binary tree and cloning. My cloning algorithm is similar to yours but with one difference.
    In my class Tree defined as:
    class Tree<T extends Comparable>
    I have:
        private void deepCopyLeft(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mLeft = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mLeft);
            deepCopyRight(src.mRight, dest.mLeft);
        private void deepCopyRight(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mRight = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mRight);
            deepCopyRight(src.mRight, dest.mRight);
        public Tree<T> deepCopy() {
            if (root == null) return new Tree<T>();
            TreeNode<T> newRoot = new TreeNode<T>(root.mValue);
            deepCopyLeft(root.mLeft, newRoot);
            deepCopyRight(root.mRight, newRoot);
            return new Tree<T>(newRoot);
        }Its a similar recursive idea, but with 2 extra functions. I hope that helps. I don't have time right now to pinpoint the problem in your routine. Good luck.

  • Recover a Binary Tree

    Ok people I need help!
    I want to create, from a pre-order and in-order sequences, the post-order sequence! Obviously there are no repeated elements (characters from A to Z at this case).
    The tree root it's the first character from pre-order and after that it's easy to take left and right sequences.
    I found an interesting explanation: http://www.dcs.kcl.ac.uk/staff/pinz...st/html/l7.html
    I've tried everything to make it recursive I think that's the best way to do it but somehow I can't make it work! My last code:
    import java.io.*;
    import java.util.*;
    public class Problem
            static String readLn (int maxLg)  // utility function to read from stdin
                byte lin[] = new byte [maxLg];
                int lg = 0, car = -1;
                try
                    while (lg < maxLg)
                        car = System.in.read();
                        if ((car < 0) || (car == '\n')) break;
                        lin [lg++] += car;
                catch (IOException e)
                    return (null);
                if ((car < 0) && (lg == 0)) return (null);  // eof
                return (new String (lin, 0, lg));
            public static void main (String []args)
                    for (int set = Integer.parseInt(readLn(10).trim()); set != 0; set--)
                            StringTokenizer tok = new StringTokenizer(readLn(100).trim()," ");
                            String preOrd = tok.nextToken();
                            String inOrd = tok.nextToken();
                            char root = preOrd.charAt(0);
                            BinaryNode tree = new BinaryNode(root);
                            // Left and right from inOrd
                            tok = new StringTokenizer(inOrd,Character.toString(root));
                            String inOrdLeft = tok.nextToken();
                            String inOrdRight = tok.nextToken();
                            // Take left and right from preOrd
                            String preOrdLeft = preOrd.substring(1,inOrdLeft.length()+1);
                            String preOrdRight = preOrd.substring(inOrdLeft.length()+1);
                            tree.left = work (preOrdLeft, 0, inOrdLeft);
                            tree.right = work (preOrdRight, 0, inOrdRight);
                            tree.printPostOrder();
                            System.out.println();
            public static BinaryNode work (String preOrd, int preOrdPoint, String inOrd)
                    char    nodeChr = preOrd.charAt(preOrdPoint);
                    String  nodeStr = Character.toString(nodeChr);
                    //System.out.println("Root: "+nodeStr+" preOrd: "+preOrd+" inOrd: "+inOrd);
                    BinaryNode tempTree = new BinaryNode(nodeChr);
                    StringTokenizer tok = new StringTokenizer(inOrd,nodeStr);  
                    try
                            String newInOrdLeft = tok.nextToken();
                            if (newInOrdLeft.length() == 1) { tempTree.left = new BinaryNode(newInOrdLeft.toCharArray()[0]); }
                            else if (newInOrdLeft.length() != 0) { tempTree.left = work(preOrd, preOrdPoint+1, newInOrdLeft); }
                    catch (NoSuchElementException e) {}
                    try
                            String newInOrdRight = tok.nextToken();
                            if (newInOrdRight.length() == 1) { tempTree.right = new BinaryNode(newInOrdRight.toCharArray()[0]); }
                            else if (newInOrdRight.length() != 0) { tempTree.right = work(preOrd, preOrdPoint+1, newInOrdRight); }
                    catch (NoSuchElementException e) {}
                    return tempTree;
    class BinaryNode
            char chr;
            BinaryNode left = null;
            BinaryNode right = null;
            BinaryNode()
            BinaryNode(char c)
                    this(c, null, null);
            BinaryNode(char c, BinaryNode lt, BinaryNode rt)
                    chr = c;
                    left = lt;
                    right = rt;
            static int size(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return size(t.left) + 1 + size(t.right); }
            static int height(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return 1 + Math.max(BinaryNode.height(t.left), BinaryNode.height(t.right)); }
            void printPostOrder () {
                    if( left != null )
                            left.printPostOrder( ); // Left
                    if( right != null )
                            right.printPostOrder( ); // Right
                    System.out.print(chr); // Node
            static BinaryNode insert (char c, BinaryNode t)
                    Character tmp = new Character(c);
                    if (t == null)
                            t = new BinaryNode(c, null, null);
                    else if (tmp.compareTo(new Character(t.chr)) < 0)
                            t.left = insert(c, t.left );
                    else if (tmp.compareTo(new Character(t.chr)) > 0)
                            t.right = insert(c, t.right);
                    return t;
    }

    I don't know if this is a translation of your C code, but it can reconstruct any binary tree (with letters as nodes and no duplicates) from preorder and inorder traversals. Hope it helps.
    import java.util.*;
    public class ReconstructTree {
        public ReconstructTree() {
        public static void main(String[] args)
            String preorder = "ABDGKLRVWSXCEHMNFIOTUJPYQZ";
            String inorder = "KGVRWLSXDBAMHNECTOUIFPYJZQ";
            Map table = new HashMap();
            Map table2 = new HashMap();
            for(int i=0; i<inorder.length(); i++)
                table.put("" + inorder.charAt(i), new Integer(i));
                table2.put(new Integer(i), "" + inorder.charAt(i));
            List temppreorder = new ArrayList();
            for(int i=0; i<preorder.length(); i++)
                temppreorder.add(table.get("" + preorder.charAt(i)));
            Node root = constructTree(temppreorder);
            printPostOrder(root, table2);
        public static void printPostOrder(Node root, Map table)
            if(root == null)
                return;
            Node left = root.getLeft();
            Node right = root.getRight();
            printPostOrder(left, table);
            printPostOrder(right, table);
            System.out.print(table.get(new Integer(Integer.parseInt("" + root.getValue()))));
        public static Node constructTree(List preorder)
            Iterator it = preorder.iterator();
            int r = ((Integer)it.next()).intValue();
            Node root = new Node(r);
            Node node = root;
            while(it.hasNext())
                node = root;
                int a = ((Integer)it.next()).intValue();
                while(true)
                    r = node.getValue();
                    if(a < r)
                        if(node.getLeft() == null)
                            node.setLeft(new Node(a));
                            break;
                        else
                            node = node.getLeft();
                    else
                        if(node.getRight() == null)
                            node.setRight(new Node(a));
                            break;
                        else
                            node = node.getRight();
            return root;
        public static class Node
            private Node left = null;
            private Node right = null;
            private int value;
            public Node(int v)
                value = v;
            public int getValue()
                return value;
            public Node getLeft()
                return left;
            public Node getRight()
                return right;
            public void setLeft(Node l)
                left = l;
            public void setRight(Node r)
                right = r;
    }

  • Emptying a Binary Tree

    Hello,
    The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
    public class MyBinaryTree implements BinaryTree {
       private BinaryTreeNode root;
       protected static int numNodes;
       private static String tree = "";
        * Constructor that creates a binary tree with a root.
        * @param r The root node
        * @param num The number of nodes
       public MyBinaryTree(BinaryTreeNode r, int num) {
          root = r;
          numNodes = num;
        * Method to make the binary tree empty.
       public void makeEmpty() {
          root.left = null;
          root.right = null;
          root = new BinaryTreeNode(null,null,null,null,null);
          numNodes = 0;
        * Method to make a root with key k and element el.
        * @param k The key of the root
        * @param el The element in the root
       public void makeRoot(Comparable k, Object el) {
          root = new BinaryTreeNode(k,el);
          numNodes++;
        * Method to return the root of the binary tree.
        * @return The root of the tree
       public BinaryTreeNode root() {
          return root;
        * Method to return the left child of a node.
        * @param node The node whose left child is wanted.
        * @return The left child of the node
        * @see NoNodeException
       public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
          if (node.left == null) throw new NoNodeException("No left child!");
          else return node.leftChild();
        * Method to set the left child of node "node".
        * @param node The node to be given a left child
        * @param child The node to be set as left child
       public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setLeftChild(child);
          numNodes++;
        * Method to return the right child of a node.
        * @param node The node whose right child is wanted.
        * @return The right child of the node
        * @see NoNodeException
       public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
          if (node.right == null) throw new NoNodeException("No right child!");
          else return node.rightChild();
        * Method to set the right child of node "node".
        * @param node The node to be given a right child
        * @param child The node to be set as right child
       public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setRightChild(child);
          numNodes++;
        * Method to return the parent of a node.
        * @param node The node whose parent is wanted.
        * @return The parent of the node
        * @see NoNodeException
       public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
          if (node.p == null) throw new NoNodeException("No parent!");
          else return node.parent();
        * Method to set the parent of node "node".
        * @param node The node to be given a parent
        * @param pt The node to be set as parent
       public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
          node.setParent(pt);
          numNodes++;
        * Method to return the key of the specified node.
        * @param node The node with the key to be returned
        * @return The key of the node
       public Comparable getKey(BinaryTreeNode node) {
          return node.getKey();
        * Method to set the key of the specified node.
        * @param node The node for which the key will be set.
        * @param k The key to be set.
       public void setKey(BinaryTreeNode node, Comparable k) {
          node.setKey(k);
        * Method to get the element in the specified node.
        * @param node The node with the element to be returned.
        * @return The element in the node.
       public Object getElement(BinaryTreeNode node) {
          return node.getElement();
        * Method to put an element into the specified node.
        * @param node The node that will have an element put in it.
        * @param o The element to be inserted.
       public void setElement(BinaryTreeNode node, Object o) {
          node.setElement(o);
        * Method to add a left child to the specified node.
        * @param theNode The node that the left child will be added to.
        * @param k The key associated with the left child.
        * @param el The element in the left child.
       public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setLeftChild(temp);
          numNodes++;
        * Method to add a right child to the specified node.
        * @param theNode The node that the right child will be added to.
        * @param k The key associated with the right child.
        * @param el The element in the right child.
       public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setRightChild(temp);
          numNodes++;
        * Method to remove the left child of the specified node.
        * @param theNode The node which the left child will be removed.
       public void removeLeftChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.left)).p = null;
          theNode.left = null;
          numNodes--;
        * Method to remove the right child of the specified node.
        * @param theNode The node which the right child will be removed.
       public void removeRightChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.right)).p = null;
          theNode.right = null;
          numNodes--;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
       private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
          tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
          return tree;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
        * @param pos The current position in the tree.
        * @return A tree with an asterix beside the current position
       private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
                                           BinaryTreeNode pos) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
          if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
          else tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
          return tree;
        * Method to return a String representation of the binary tree.
        * @return String representation of the binary tree
       public String toString() {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint(temp,root);
        * Method to return a String of the binary tree with an asterix beside the
        * current position.
        * @param currentPosition The current position.
        * @return A String of the tree with an asterix by the current position
       public String toString(BinaryTreeNode currentPosition) {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint2(temp,root,currentPosition);
    }Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?

    Here is the BinaryTreeNode code.
    public class BinaryTreeNode {
        // Instance variables (Note: they are all "private")
        protected Comparable key;           // The key at this node
        protected Object element;          // The data at this node
        protected BinaryTreeNode left;     // Left child
        protected BinaryTreeNode right;    // Right child
        protected BinaryTreeNode p;        // The Parent
        // Constructors
        BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
                        BinaryTreeNode rt, BinaryTreeNode pt  ) {
            key      = theKey;
            element  = theElement;
            left     = lt;
            right    = rt;
            p        = pt;
        BinaryTreeNode( Comparable theKey, Object theElement) {
            key      = theKey;
            element  = theElement;
            left     = null;
            right    = null;
            p        = null;
        // return the key attached to this node
        public Comparable getKey() {
            return key;
        // set the key attached to this node to be Comparable k
        public void setKey(Comparable k) {
            key = k;
        // return the element attached to this node
        public Object getElement() {
            return element;
        // set the element attached to this node to be Object o
        public void setElement(Object o) {
            element = o;
        // return left child
        public BinaryTreeNode leftChild() {
            return left;
        // set left child to be node n
        public void setLeftChild(BinaryTreeNode n) {
            left = n;
        // return right child
        public BinaryTreeNode rightChild() {
            return right;
        // set right child to be node n
        public void setRightChild(BinaryTreeNode n) {
            right = n;
        // return parent
        public BinaryTreeNode parent() {
            return p;
        // set parent to be node n
        public void setParent(BinaryTreeNode n) {
            p = n;
    }

Maybe you are looking for

  • Can't change the connection string of SSIS package with derived columns?

    We upgraded SQL server 2008 to 2012, copied and converted all SSIS packages from Visual Studio 2008 to 2010.  When I opened a package in VS 2010 and tried to change the connection string, in the local connection managers, if the data source is anothe

  • Want to check page is displayed on browser or not ?

    In my code: in every half an hour it opens my browser and access a website(just like www.yahoo.com). I want, in any case if page not displayed it make a file and saved it on my pc. How can i check the page is displayed or not ?

  • Relation between MSEG table and movement types in 2lis_03_bf

    Hi all, May i know the relation between MSEG table and 2lis_03 _bf xtractor stock type/stockcategory where we see the informarion in r/3 side for this, you answers gets rewarded. regards, Dan.

  • Stream Configuration between different 11gr1 and 11gr2

    I have oracle downstream set-up between two DBs both are 11gr1, i want to upgrade my my target DB to 11gr2. I want to ask whether my streams set-up would work after this or not. OR Is it possible have streaming between two version of oracle. I shall

  • Change calling plan

    We are on a 1400 minute calling plan and are not using nearly as many minutes as we used to. We want to scale back down to 750 minutes. I have been told repeatedly by Verizon I can do this online, but I cannot find where. Under the Plan area of My Ve