Building a binary tree from a string

I'm having trouble building a binary tree with shape described in a string.
00 - means both left and right subtrees are empty;
01 - means that the left is empty, and the right is not;
10 - right is empty, left is not
11 - neither are empty
public BinaryTree(String s, Iterator it) {
This constructor is supposed to build the binary tree of the specified shape and fills it with values. THe values come from Iterator it, and are placed into the tree in preorder fashion.
I have to complete this constructor but I don't really know what to do. I was thinking I could use indexOf somehow. Any help would be greatly appreciated.
Thanks,
Mike

I'd build it like this (this is from the top of my head, so no typo-free-warranties etc.) -- public class Tree {
   private Object data;
   private Tree left= null;
   private Tree right= null;
   private Tree(StringReader sr, Iterator di) {
      char l= (char)sr.read(); // left and right subtree indicators
      char r= (char)sr.read();
      data= di.next(); // set data for this node
      if (l == '1') left= new Tree(sr, di); // build left subtree
      if (r == '1') right= new Tree(sr, di); // build right subtree
   public Tree(String s, Iterator di) {
      this(new StringReader(s), di);
} Note that the private constructor (the one that does all the work) doesn't handle incorrect strings
at all, i.e. it'll crash horribly when the string passes contains, say an odd number of characters
is is simply passing incorrect construction information. Also note that the Iterator must be able
to iterate over enough elements to be set.
kind regards,
Jos

Similar Messages

  • Traverse a binary tree from root to every branch

    I have a couple of other questions. I need to get all the different combinations of a binary tree and store them into a data structure. For the example in the code below, the combinations would be:
    1) Start, A1, A2, A3, B1, B2, B3
    2) Start, A1, A2, B1, A3, B2, B3
    3) Start, A1, A2, B1, B2, A3, B3
    4) Start, A1, A2, B1, B2, B3, A3
    5) Start, A1, B1, A2, A3, B2, B3
    etc.
    I understand that this is very similar to the preorder traversal, but preorder does not output the parent nodes another time when the node splits into a left and right node. Any suggestions?
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package binarytreetest;
    import java.util.ArrayList;
    import java.util.Iterator;
    * @author vluong
    public class BinaryTreeTest {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            int countA = 0;
            int countB = 0;
            ArrayList listA = new ArrayList();
            ArrayList listB = new ArrayList();
            listA.add("A1");
            listA.add("A2");
            listA.add("A3");
            listB.add("B1");
            listB.add("B2");
            listB.add("B3");
            //listB.add("B1");
            Node root = new Node("START");
            constructTree(root, countA, countB, listA, listB);
            //printInOrder(root);
            //printFromRoot(root);
        public static class Node{
            private Node left;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        public static void constructTree(Node node, int countA, int countB, ArrayList listA, ArrayList listB){
            if(countA < listA.size()){
                if(node.left == null){
                    System.out.println("There is no left node. CountA is " + countA);
                    System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.left = new Node(listA.get(countA).toString()); 
                    constructTree(node.left, countA+1, countB, listA, listB);   
                }else{
                    System.out.println("There is a left node. CountA + 1 is " + countA+1);
                    constructTree(node.left, countA+1, countB, listA, listB);   
            if(countB < listB.size()){
                if(node.right == null){
                    System.out.println("There is no right node. CountB is " + countB);
                    System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.right = new Node(listB.get(countB).toString());
                    constructTree(node.right, countA, countB+1, listA, listB);
                }else{
                    System.out.println("There is a right node. CountB + 1 is " + countB+1);
                    constructTree(node.right, countA, countB+1, listA, listB);
        }My second question is, if I need to add another list (listC) and find all the combinations of List A, listB and list C, is it correct to define the node class as
    public static class Node{
            private Node left;
            private Node mid;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        }Node left = listA, Node mid = listB, Node right = listC
    The code for the 3 lists is below.
    3 lists (A, B, C):
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package binarytreetest;
    import java.util.ArrayList;
    * @author vluong
    public class BinaryTreeTest {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            insert(root, "A1");
            insert(root, "A2");
            insert(root, "B1");
            insert(root, "B2"); 
            insert(root, "A2");
            int countA = 0;
            int countB = 0;
            int countC = 0;
            ArrayList listA = new ArrayList();
            ArrayList listB = new ArrayList();
            ArrayList listC = new ArrayList();
            listA.add("A1");
            listA.add("A2");
            //listA.add("A3");
            listB.add("B1");
            listB.add("B2");
            //listB.add("B3");
            //listB.add("B1");
            listC.add("C1");
            listC.add("C2");
            Node root = new Node("START");
            constructTree(root, countA, countB, countC, listA, listB, listC);
            //ConstructTree(root, countA, countB, listA, listB);
            //ConstructTree(root, countA, countB, listA, listB);
            printInOrder(root);
            //printFromRoot(root);
        public static class Node{
            private Node left;
            private Node mid;
            private Node right;
            private String value;
            public Node(String value){
                this.value = value;
        public static void constructTree(Node node, int countA, int countB, int countC, ArrayList listA, ArrayList listB, ArrayList listC){
            if(countA < listA.size()){
                if(node.left == null){
                    System.out.println("There is no left node. CountA is " + countA);
                    System.out.println("Created new node with value: " + listA.get(countA).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.left = new Node(listA.get(countA).toString()); 
                    constructTree(node.left, countA+1, countB, countC, listA, listB, listC);   
                }else{
                    System.out.println("There is a left node. CountA + 1 is " + countA+1);
                    constructTree(node.left, countA+1, countB, countC, listA, listB, listC);   
            if(countB < listB.size()){
                if(node.mid == null){
                    System.out.println("There is no mid node. CountB is " + countB);
                    System.out.println("Created new node with value: " + listB.get(countB).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.mid = new Node(listB.get(countB).toString());
                    constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
                }else{
                    System.out.println("There is a right node. CountB + 1 is " + countB+1);
                    constructTree(node.mid, countA, countB+1, countC, listA, listB, listC);
            if(countC < listC.size()){
                if(node.right == null){
                    System.out.println("There is no right node. CountC is " + countC);
                    System.out.println("Created new node with value: " + listC.get(countC).toString() + " with parent, "
                            + node.value);
                    System.out.println();
                    node.right = new Node(listC.get(countC).toString());
                    constructTree(node.right, countA, countB, countC+1, listA, listB, listC);
                }else{
                    System.out.println("There is a right node. CountC + 1 is " + countC+1);
                    constructTree(node.mid, countA, countB, countC+1, listA, listB, listC);
        }Thank you in advance!

    It looks to me like you are interleaving two lists. It looks like you are doing this while leaving the two subsequences in their original order.
    If that is in fact what you are doing, then this is just a combinatorics problem. Here is psuedo code (NOT java!)
    List path = new List();
    show(List A, int a, List B, int b, path){
      if(a >= A.length() && b >= b.length()){
        spew(path);
      } else {
        if(a < A.length()){path.push(A[a]); show(A,a+1,B,b,); path.pop();}
        if(b < B.length()){path.push(B); show(A,a,B,b+1,); path.pop();}
    show(A, 0, B, 0);
    In order to interleave 3 lists, you would add C and c arguments to the function and you would add one more line in the else block.

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

  • 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

  • Looking for code creating binary tree from expression(prefix)!

    I wanna use expression to generate binary expression tree. For example:
    I have expression in string: 1+2*3;
    then generate a tree like:
    +
    1 *
    2 3
    does some body have example code?

    sniff sniff I thought we were having lasagna? Smells like homework!

  • How to build a time stamp from a string

    I have the date-time information stored in a string and I want to build a time stamp to make a plot with the date-time in the X axys. Is there a way to do this??
    thanking in advance...
    crimolvic

    See attached vi.  You may have to modify depending on the order your string.
    - tbob
    Inventor of the WORM Global
    Attachments:
    DateTimeMOD[1].vi ‏34 KB

  • Trouble with Frank Nimph Building a hierarchical tree from recursive table

    I copy the example, but when i run it i get the error:
    javax.faces.el.EvaluationException: javax.faces.FacesException: javax.faces.FacesException: Can't instantiate class: 'vuo.view.TreeHandler'.. class vuo.view.TreeHandler : java.lang.ClassCastException: oracle.jbo.domain.Number
    Caused by: java.lang.ClassCastException: oracle.jbo.domain.Number     at vuo.view.TreeHandler.populateTreeNodes(TreeHandler.java:58)
    This is line 58 of TreeHandler.java : employeeNode.setEmployee_id((Number)row.getAttribute("EmployeeId"));
    The problem is that i couldn't import oracle.jbo.domain.Number; like in the files TreeHandler.java and GenericTreeNode.java because when i type import oracle.jbo.domain.Number;on my java classes It doesn't compile, in GenericTreeNode does not recongnize:
    private Number employee_id;
    private Number manager_id;
    private Number salary;
    and in TreeHandler it said Number not found.
    So i comment the import oracle.jbo.domain.Number; on both classes and compile ok, but when i run the page i get the error:
    javax.faces.el.EvaluationException: javax.faces.FacesException: javax.faces.FacesException: Can't instantiate class: 'vuo.view.TreeHandler'.. class vuo.view.TreeHandler : java.lang.ClassCastException: oracle.jbo.domain.Number
    So what can i do?
    Thanks.

    Hi,
    as you copied the code, male sure that your classes import statement has oracle.jbo.Number and not java.lang.Number in it. It seems that you try to cast oracle.jbo.Number to java.lang.Number. Note that oracle.jbo.Number requires the ADF Business Component runtime libraries to be selected for the ViewLayer project (see project libraries)
    Frank

  • Need Help with a String Binary Tree

    Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
    plssss... someone pls help me on this
    here is my code now:
    // TreeApp.java
    // demonstrates binary tree
    // to run this program: C>java TreeApp
    import java.io.*; // for I/O
    import java.util.*; // for Stack class
    import java.lang.Integer; // for parseInt()
    class Node
         //public int iData; // data item (key)
         public String iData;
         public double dData; // data item
         public Node leftChild; // this node's left child
         public Node rightChild; // this node's right child
         public void displayNode() // display ourself
              System.out.print('{');
              System.out.print(iData);
              System.out.print(", ");
              System.out.print(dData);
              System.out.print("} ");
    } // end class Node
    class Tree
         private Node root; // first node of tree
         public Tree() // constructor
         { root = null; } // no nodes in tree yet
         public Node find(int key) // find node with given key
         {                           // (assumes non-empty tree)
              Node current = root; // start at root
              while(current.iData != key) // while no match,
                   if(key < current.iData) // go left?
                        current = current.leftChild;
                   else // or go right?
                        current = current.rightChild;
                   if(current == null) // if no child,
                        return null; // didn't find it
              return current; // found it
         } // end find()
         public Node recfind(int key, Node cur)
              if (cur == null) return null;
              else if (key < cur.iData) return(recfind(key, cur.leftChild));
              else if (key > cur.iData) return (recfind(key, cur.rightChild));
              else return(cur);
         public Node find2(int key)
              return recfind(key, root);
    public void insert(int id, double dd)
    Node newNode = new Node(); // make new node
    newNode.iData = id; // insert data
    newNode.dData = dd;
    if(root==null) // no node in root
    root = newNode;
    else // root occupied
    Node current = root; // start at root
    Node parent;
    while(true) // (exits internally)
    parent = current;
    if(id < current.iData) // go left?
    current = current.leftChild;
    if(current == null) // if end of the line,
    {                 // insert on left
    parent.leftChild = newNode;
    return;
    } // end if go left
    else // or go right?
    current = current.rightChild;
    if(current == null) // if end of the line
    {                 // insert on right
    parent.rightChild = newNode;
    return;
    } // end else go right
    } // end while
    } // end else not root
    } // end insert()
    public void insert(String id, double dd)
         Node newNode = new Node(); // make new node
         newNode.iData = id; // insert data
         newNode.dData = dd;
         if(root==null) // no node in root
              root = newNode;
         else // root occupied
              Node current = root; // start at root
              Node parent;
              while(true) // (exits internally)
                   parent = current;
                   //if(id < current.iData) // go left?
                   if(id.compareTo(current.iData)>0)
                        current = current.leftChild;
                        if(current == null) // if end of the line,
                        {                 // insert on left
                             parent.leftChild = newNode;
                             return;
                   } // end if go left
                   else // or go right?
                        current = current.rightChild;
                        if(current == null) // if end of the line
                        {                 // insert on right
                             parent.rightChild = newNode;
                             return;
                   } // end else go right
              } // end while
         } // end else not root
    } // end insert()
         public Node betterinsert(int id, double dd)
              // No duplicates allowed
              Node return_val = null;
              if(root==null) {       // no node in root
                   Node newNode = new Node(); // make new node
                   newNode.iData = id; // insert data
                   newNode.dData = dd;
                   root = newNode;
                   return_val = root;
              else // root occupied
                   Node current = root; // start at root
                   Node parent;
                   while(current != null)
                        parent = current;
                        if(id < current.iData) // go left?
                             current = current.leftChild;
                             if(current == null) // if end of the line,
                             {                 // insert on left
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.leftChild = newNode;
                        } // end if go left
                        else if (id > current.iData) // or go right?
                             current = current.rightChild;
                             if(current == null) // if end of the line
                             {                 // insert on right
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.rightChild = newNode;
                        } // end else go right
                        else current = null; // duplicate found
                   } // end while
              } // end else not root
              return return_val;
         } // end insert()
         public boolean delete(int key) // delete node with given key
              if (root == null) return false;
              Node current = root;
              Node parent = root;
              boolean isLeftChild = true;
              while(current.iData != key) // search for node
                   parent = current;
                   if(key < current.iData) // go left?
                        isLeftChild = true;
                        current = current.leftChild;
                   else // or go right?
                        isLeftChild = false;
                        current = current.rightChild;
                   if(current == null)
                        return false; // didn't find it
              } // end while
              // found node to delete
              // if no children, simply delete it
              if(current.leftChild==null &&
                   current.rightChild==null)
                   if(current == root) // if root,
                        root = null; // tree is empty
                   else if(isLeftChild)
                        parent.leftChild = null; // disconnect
                   else // from parent
                        parent.rightChild = null;
              // if no right child, replace with left subtree
              else if(current.rightChild==null)
                   if(current == root)
                        root = current.leftChild;
                   else if(isLeftChild)
                        parent.leftChild = current.leftChild;
                   else
                        parent.rightChild = current.leftChild;
              // if no left child, replace with right subtree
              else if(current.leftChild==null)
                   if(current == root)
                        root = current.rightChild;
                   else if(isLeftChild)
                        parent.leftChild = current.rightChild;
                   else
                        parent.rightChild = current.rightChild;
                   else // two children, so replace with inorder successor
                        // get successor of node to delete (current)
                        Node successor = getSuccessor(current);
                        // connect parent of current to successor instead
                        if(current == root)
                             root = successor;
                        else if(isLeftChild)
                             parent.leftChild = successor;
                        else
                             parent.rightChild = successor;
                        // connect successor to current's left child
                        successor.leftChild = current.leftChild;
                        // successor.rightChild = current.rightChild; done in getSucessor
                   } // end else two children
              return true;
         } // end delete()
         // returns node with next-highest value after delNode
         // goes to right child, then right child's left descendents
         private Node getSuccessor(Node delNode)
              Node successorParent = delNode;
              Node successor = delNode;
              Node current = delNode.rightChild; // go to right child
              while(current != null) // until no more
              {                                 // left children,
                   successorParent = successor;
                   successor = current;
                   current = current.leftChild; // go to left child
              // if successor not
              if(successor != delNode.rightChild) // right child,
              {                                 // make connections
                   successorParent.leftChild = successor.rightChild;
                   successor.rightChild = delNode.rightChild;
              return successor;
         public void traverse(int traverseType)
              switch(traverseType)
              case 1: System.out.print("\nPreorder traversal: ");
                   preOrder(root);
                   break;
              case 2: System.out.print("\nInorder traversal: ");
                   inOrder(root);
                   break;
              case 3: System.out.print("\nPostorder traversal: ");
                   postOrder(root);
                   break;
              System.out.println();
         private void preOrder(Node localRoot)
              if(localRoot != null)
                   localRoot.displayNode();
                   preOrder(localRoot.leftChild);
                   preOrder(localRoot.rightChild);
         private void inOrder(Node localRoot)
              if(localRoot != null)
                   inOrder(localRoot.leftChild);
                   localRoot.displayNode();
                   inOrder(localRoot.rightChild);
         private void postOrder(Node localRoot)
              if(localRoot != null)
                   postOrder(localRoot.leftChild);
                   postOrder(localRoot.rightChild);
                   localRoot.displayNode();
         public void displayTree()
              Stack globalStack = new Stack();
              globalStack.push(root);
              int nBlanks = 32;
              boolean isRowEmpty = false;
              System.out.println(
              while(isRowEmpty==false)
                   Stack localStack = new Stack();
                   isRowEmpty = true;
                   for(int j=0; j<nBlanks; j++)
                        System.out.print(' ');
                   while(globalStack.isEmpty()==false)
                        Node temp = (Node)globalStack.pop();
                        if(temp != null)
                             System.out.print(temp.iData);
                             localStack.push(temp.leftChild);
                             localStack.push(temp.rightChild);
                             if(temp.leftChild != null ||
                                  temp.rightChild != null)
                                  isRowEmpty = false;
                        else
                             System.out.print("--");
                             localStack.push(null);
                             localStack.push(null);
                        for(int j=0; j<nBlanks*2-2; j++)
                             System.out.print(' ');
                   } // end while globalStack not empty
                   System.out.println();
                   nBlanks /= 2;
                   while(localStack.isEmpty()==false)
                        globalStack.push( localStack.pop() );
              } // end while isRowEmpty is false
              System.out.println(
         } // end displayTree()
    } // end class Tree
    class TreeApp
         public static void main(String[] args) throws IOException
              int value;
              double val1;
              String Line,Term;
              BufferedReader input;
              input = new BufferedReader (new FileReader ("one.txt"));
              Tree theTree = new Tree();
         val1=0.1;
         while ((Line = input.readLine()) != null)
              Term=Line;
              //val1=Integer.parseInt{Term};
              val1=val1+1;
              //theTree.insert(Line, val1+0.1);
              val1++;
              System.out.println(Line);
              System.out.println(val1);          
    theTree.insert(50, 1.5);
    theTree.insert(25, 1.2);
    theTree.insert(75, 1.7);
    theTree.insert(12, 1.5);
    theTree.insert(37, 1.2);
    theTree.insert(43, 1.7);
    theTree.insert(30, 1.5);
    theTree.insert(33, 1.2);
    theTree.insert(87, 1.7);
    theTree.insert(93, 1.5);
    theTree.insert(97, 1.5);
              theTree.insert(50, 1.5);
              theTree.insert(25, 1.2);
              theTree.insert(75, 1.7);
              theTree.insert(12, 1.5);
              theTree.insert(37, 1.2);
              theTree.insert(43, 1.7);
              theTree.insert(30, 1.5);
              theTree.insert(33, 1.2);
              theTree.insert(87, 1.7);
              theTree.insert(93, 1.5);
              theTree.insert(97, 1.5);
              while(true)
                   putText("Enter first letter of ");
                   putText("show, insert, find, delete, or traverse: ");
                   int choice = getChar();
                   switch(choice)
                   case 's':
                        theTree.displayTree();
                        break;
                   case 'i':
                        putText("Enter value to insert: ");
                        value = getInt();
                        theTree.insert(value, value + 0.9);
                        break;
                   case 'f':
                        putText("Enter value to find: ");
                        value = getInt();
                        Node found = theTree.find(value);
                        if(found != null)
                             putText("Found: ");
                             found.displayNode();
                             putText("\n");
                        else
                             putText("Could not find " + value + '\n');
                        break;
                   case 'd':
                        putText("Enter value to delete: ");
                        value = getInt();
                        boolean didDelete = theTree.delete(value);
                        if(didDelete)
                             putText("Deleted " + value + '\n');
                        else
                             putText("Could not delete " + value + '\n');
                        break;
                   case 't':
                        putText("Enter type 1, 2 or 3: ");
                        value = getInt();
                        theTree.traverse(value);
                        break;
                   default:
                        putText("Invalid entry\n");
                   } // end switch
              } // end while
         } // end main()
         public static void putText(String s)
              System.out.print(s);
              System.out.flush();
         public static String getString() throws IOException
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader br = new BufferedReader(isr);
              String s = br.readLine();
              return s;
         public static char getChar() throws IOException
              String s = getString();
              return s.charAt(0);
         public static int getInt() throws IOException
              String s = getString();
              return Integer.parseInt(s);
    } // end class TreeApp

    String str = "Hello";
              int index = 0, len = 0;
              len = str.length();
              while(index < len) {
                   System.out.println(str.charAt(index));
                   index++;
              }

  • How to build n Tree from Vector

    Hi,
    i just want to build an n Tree from Vector.
    the Vector contains the elements {1,2,3,4}
    the tree should be like this (actually it should not be limited to 3 child, but just as an Example)
    i will be happy to use the jTree from Sun
    ++1
    +++2
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    +++2
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    +++2
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    ++++3
    +++++4
    +++++4
    +++++4
    any Ideas?
    thanx.

    Massive crosspost. Answer here if you must.
    http://forum.java.sun.com/thread.jsp?forum=4&thread=444422

  • A Binary Tree Implementation in ABAP

    Hi,
    Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
    Thanks,
    Manjula.

    Hi manjula,
    This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It. 
    It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing  through the tree.
    For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
    *& Report YBINTREE - Build/Print Binary Tree of numbers *
    report ybintree .
    types: begin of stree,
    value type i,
    left type ref to data,
    right type ref to data,
    end of stree.
    data: tree type stree.
    data: int type i.
    data: begin of rnd occurs 0,
    num type i,
    end of rnd.
    start-of-selection.
    do 100 times.
    generate random number between 0 and 100
    call function 'RANDOM_I4'
    exporting
    rnd_min = 0
    rnd_max = 100
    importing
    rnd_value = int.
    store numbers
    rnd-num = int.
    append rnd.
    build binary tree of random numbers
    perform add_value using tree int.
    enddo.
    stored numbers are sorted for comparison
    sort rnd by num.
    print sorted random numbers
    write: / 'Sorted Numbers'.
    write: / '=============='.
    skip.
    loop at rnd.
    write: rnd-num.
    endloop.
    skip.
    print binary tree. This should give the same result
    as the one listed from the internal table
    write: / 'Binary Tree List'.
    write: / '================'.
    skip.
    perform print_value using tree.
    skip.
    *& Form add_value
    text - Build tree with value provided
    -->TREE text
    -->VAL text
    form add_value using tree type stree val type i.
    field-symbols: <ltree> type any.
    data: work type stree.
    if tree is initial. "When node has no values
    tree-value = val. " assign value
    clear: tree-left, tree-right.
    create data tree-left type stree. "Create an empty node for left
    create data tree-right type stree. "create an empty node for right
    else.
    if val le tree-value. "if number is less than or equal
    assign tree-left->* to <ltree>. "assign the left node to fs
    call add_value recursively with left node
    perform add_value using <ltree> val.
    else. "if number is greater
    assign tree-right->* to <ltree>. "assign the right node to fs
    call add_value recursively with right node
    perform add_value using <ltree> val.
    endif.
    endif.
    endform. "add_value
    *& Form print_value
    text - traverse tree from left-mid-right order
    automatically this will be sorted list
    -->TREE text
    form print_value using tree type stree.
    field-symbols: <ltree> type any.
    if tree is initial. "node is empty
    else. "non-empty node
    assign tree-left->* to <ltree>. "left node
    perform print_value using <ltree>. "print left
    write: tree-value. "print the current value
    assign tree-right->* to <ltree>. "right node
    perform print_value using <ltree>. "print right
    endif.
    endform. "print_value
    pls reward if helps,
    regards.

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

  • JAXB: Creating Java content tree from scratch - examples?

    I'm trying to create XML output by building the content tree from scratch (using a the DDI schema which is fairly complex). I don't have any existing XML instances. Sample application 3 in Sun's JAXB tutorial doesn't give enough info about how to relate the nodes to create the heirarchy. I can create the root node and set it's attributes OK, but then the practical info runs out.
    Can anyone point me at some good practical examples? (i.e. not those of the "How to play the quitar: Put your fingers on the frets and move your other hand around" genre).
    Thanks in advance.

    I don't have examples, but the main thing to remember is that you should use the ObjectFactory to create all of the objects in your tree. That's important.
    You must use the element object class for the root node, but you can use type object classes for all the data contained (you can use element object classes for all the nodes, if that's easier).
    Use the accessor methods to load the data into the objects you create.
    One tip that almost everyone runs into - JAXB only provides a getter for lists - use the getter to get the list, then use .add() methods to add the objects to that list.

  • Parsing XML from a String

    I have a servlet, this recieves an XML file from the client as a file input type from a html form. This XML is wrapped up in http headers and stuff. I parse the input stream from the client's http request to get a string containing the xml. This is fine.
    How do I now build an XML document from this string? The DocumentBuilder will take in files and InputStreams but I can't find anything that helps me?
    The only solution I've come up with is to write out the string to a temp file and then parse it back into a Document.
    Any ideas anyone?????

    Document doc = documentBuilder.parse(new InputSource(new StringReader(yourXMLString)));
    voila!

  • 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

  • How come I can't open a photo in CS6?

    That message shows up when I try to open an image, but I can successfully open a picture, just not the same one. What can I do to fix this?

  • Standard Extractor for Tax Details

    Hi all, Is there any standard extractor available to extract the Tax related data from the Accounting document. regards Vishu

  • Strange Error when previewing or publishing

    Hi Muse Family I am getting a very strange error when I publish to BC or when I go to preview in browser: "Adobe Muse has encountered an error.. blah blah" and then a very confusing: "There should not be such ID exists in the mapping" It forces Muse

  • Error message "Could not find active BDoc...." in "genstatus" transaction

    Hello we upgrade from CRM 2007 SP 5 to SP 9. in transaction GENSTATUS we get 2 kind of message. 1. yellow messages 2. red ERROR Generator group: GNREP                              LUTAB we already run the job  MW_GENERATE |Object Name                

  • Storing local variables

    Sorry for the simplicity of this question! If my script runs within a master function/object - all the variables are held within that object (declared locally )so don't affect the global namespace. When I look at other people's scripts - I see they d