Pretty print of a binary tree

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

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

Similar Messages

  • How to Pretty Print a Binary Tree?

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

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

  • 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

  • Any ideas on a nice BSP view pretty printer?

    Hi there,
    I am wondering whether somebody already tried to extend the SAP standard pretty printer by an own functionality which fits better for pages with mixed content, containing not only BSP-elements but also HTML-tags.
    The standard pretty printer considers everything as plain text which is not a BSP-element and leaves it unaltered. Only BSP-elements are arranged according to their tree structure.
    This produces ugly results for pages with mixed content.
    1.) Requirement
    A Pretty Printer for HTML-based BSP views should cover the following:
    (a) HTML-Tags and BSP-elements together form the chain. As in following example:
    <z:table table_id="testTab" binding="//test/gt_test" rows="5">
      <z:tableBody position="top">
        <colgroup>
          <col width="4%">
          <col width="96%">
        </colgroup>
      </z:tableBody>
      <z:column name="type" header="<%=zcl_bsp_util=>dtel_text_s('EDI_TTYP')%>"
                listPos="10"/>
      <z:column name="text" listPos="20"></z:column>
    </z:table>
    (b) Certain HTML formatting tags like I, B, etc. should not be added to the stack but be treated inline.
    (c) HTML-attribute names should be converted to lower case, the attribute values should be quoted.
    (d) Like for BSP-elements, there should be a threshold after which the attributes should appear in separate lines. Instead of a certain maximum "number of attributes", this could also be a maximum number of characters per line.
    (e) Scripting Tags (<% ... %>) should start at a new line, if the content contains new-lines.
    (f) Evaluation Scripting (<%= ... %>) should be inline, if they are contained within text nodes (and not within HTML oder BSP element nodes).
    (g) The Pretty Printer should be parametrizable (with parameters like indent-depth,... ).
    2.) Exits?
    Of course, one could always use an external HTML editor and write an add-on for that editor which produces the desired result. Or one could take the view content into the clipboard, paste it into a plain text editor like UltraEdit or TextPad which allows external commands, apply an external, self-written pretty printer to it and then paste the result back into the View. But it would be easier to use the "Pretty Printer" button directly to get the result. Therefore the question arises at which point the standard Pretty Printer Functionality could be modified or extended.
    I didn't find an exit. But the pretty-print itself is doubly-decoupled in the standard which minimizes the number of points where an extension has to be made:
    2.a) First decoupling point: The Fcode handler method pretty_printer_ext( ) in cl_o2_page is calling
    dynamically a method in cl_o2_co2_processor:
    * call pretty printer
      create object pp type ('CL_O2_CO2_PROCESSOR').
      appl_str = me->pagekey-applname.
      page_str = me->pagekey-pagekey.
      try.
          CALL METHOD pp->('PRETTY_PRINT')
            EXPORTING
              indent              = 2
              ATTRIBUTE_NORMALIZE = 'X'
              ATTRIBUTE_THRESHOLD = 2
              BSP_UNFORMATTED     = source
              appl                = appl_str
              page                = page_str
            IMPORTING
              test_ok             = test_ok
              BSP_FORMATTED       = pp_source.
        catch cx_o2_co2_exception into o2ex.
    2.b) Second decoupling point:
    The method pretty_print() of class cl_o2_co2_processor (fancy names, by the way. It seems that many former chemistry students had joined the BSP team ),
    there is a second delegation, to a local class, as follows:
      data pretty type ref to LCL_BSP_PRETTY_PRINT.
      pretty = LCL_BSP_PRETTY_PRINT=>getInstance( processor = me ).
    The real logic for doing the Pretty Print, finally, is performed in this local class.
    3.) Implementation.
    Since, up to my knowledge, there is no HTML parser in the ABAP world,
    the implementation could be based on existing HTML Parsers, like the Perl module Parser::HTML, or the Java package http://htmlparser.sourceforge.net/ . The pretty printer could then be called as external OS command.
    Are there any ideas out there? Or is there somebody who already worked in this direction?
    Regards,
    Rüdiger

    For those who are interested. I found out that the Dave Ragget's classic "HTML Tidy" (see <a href="http://tidy.sourceforge.net/">http://tidy.sourceforge.net/</a> )  is available in ABAP! There is a class CL_HTMLTIDY (at least here in my SAP_BASIS 700 system) which wraps calls of HTML Tidy by kernel modules.
    The class is undocumented, but there are 2 OSS notes of this year for it, so it might well be that it is alive.
    HTML Tidy can surely not directly be used for Pretty Printing BSP views, but for designing test cases or for doing things like HTML parsing, it might be a helpful tool.

  • How to crossover this binary tree..?

    You can view detail http://www.codeguru.com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
    [nha khoa|http://www.sieuthi77.com/main/nhakhoa.html] .com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
    I have these classes which model a tree (binary). the thing is i cant figure out how i can set the elements of individual nodes in that tree. i can get individual elements but i cannot set them due to the strucutre of the tree and how it is implemented. The changes that I make to these classes should be as less as possible, because i have an algorithm which generates the tree structure randomly, plus i can evaluate the tree easily by using recursion. The only left thing to do is CROSSOVER but how?!?
    here are the classes which model my binary tree:
    Code:
    public abstract class Node implements Cloneable{
    abstract double evaluate(VariableInput v);
    abstract String print();
    abstract int getNumberOfNodes();
    abstract ArrayList<Object> getChildren();
    @Override
    public Node clone(){
    Node copy;
    try {
    copy = (Node) super.clone();
    } catch (CloneNotSupportedException unexpected) {
    throw new AssertionError(unexpected);
    //In an actual implementation of this pattern you might now change references to
    //the expensive to produce parts from the copies that are held inside the prototype.
    return copy;
    Code:
    public class UnaryNode extends Node {
    private UnaryFunction operator;
    private Node left;
    public UnaryNode(UnaryFunction op, Node terminal) {
    operator = op;
    this.left = terminal;
    public String print(){
    String r = "(" + operator.toString()+ " " + left.print() + ")";
    return r;
    void setLeft(Node left) {
    this.left = left;
    @Override
    int getNumberOfNodes() {
    return 1 + left.getNumberOfNodes();
    Node getLeft() {
    return left;
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(this);
    arr.addAll(left.getChildren());
    return arr;
    Code:
    public class BinaryNode extends Node {
    private BinaryFunction operator;
    private Node left;
    private Node right;
    public BinaryNode(BinaryFunction op, Node left, Node right) {
    operator = op;
    this.left = left;
    this.right = right;
    public String print(){
    String r = "(" + operator.toString()+ " " + left.print() + " " + right.print()+")";
    return r;
    public void setLeft(Node left){
    this.left = left;
    public void setRight(Node right){
    this.right = right;
    @Override
    int getNumberOfNodes() {
    return 1 + left.getNumberOfNodes() + right.getNumberOfNodes();
    Node getRight() {
    return right;
    Node getLeft() {
    return left;
    @Override
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(this);
    arr.addAll(left.getChildren());
    arr.addAll(right.getChildren());
    return arr;
    public class NumericNode extends Node{
    private double value;
    public NumericNode(double v){
    value = v;
    @Override
    double evaluate(VariableInput c) {
    return value;
    public String print(){
    String r = "" + value;
    return r;
    @Override
    int getNumberOfNodes() {
    return 1;
    @Override
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(new NumericNode(value));
    return arr;
    }p.s. I have this get children method which return a list of REFERENCES to all the nodes in the tree, but if i change any of them it wont have an effect to the tree itself because they are references.
    Any ideas or codes will be much appreciated. Thanks!

    What? Changes to what a node is referencing will be reflected in the tree, unless your getChildren is returning a copy, like in NumericNode.
    Kaj

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

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

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

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

  • Reconstructing a Binary Tree

    Hi guys ;
    I have a BST class .One of its methods is preorder travesal.
    this method traverse theBinary tree in preorder and prints nodes data to a file.
    Now what i want to do is to be able to construct the binary tree by reading data from this file : keeping in mind the data nodes were saved to this file in preorder.
    Is this a possible thing to do ?
    How can I do this ?
    Is there a better way to save a binary tree to a file and the other way : read from file and construct the tree again?
    Many thanks for helping !

    I'd like to say thanks too.. it really helped me out!
    I used a few minutes (or so ;) to figure out the functions for saving and rebuilding the tree, so I thought I'd post it here, if anyone could use it. Note: this ugly pseudocode might look a little like VB.net-code, which happened completely by accident..
        Private Function SearchForLeaves(ByVal StartNode As Node, ByVal BitString As String) As String
            'Recursive function. If a leaf is found on left or right side of the branch,
            'then print the binary pattern used to get there, else call the function again on the next branch.
            Dim SavedTree As String
            With StartNode
                If .LeftChild.Type = NodeType.Leaf Then
                    Print .leftChild.Value & " " & Bitstring & "0"
                    SavedTree += "!" & .LeftChild.Value
                Else
                    SearchForLeaves(.LeftChild, BitString & "0")
                End If
                If .RightChild.Type = NodeType.Leaf Then
                    Print .leftChild.Value & " " & Bitstring & "1"
                    SavedTree += "!" & .RightChild.Value
                Else
                    SearchForLeaves(.RightChild, BitString & "1")
                End If
                SavedTree += "?"
            End With
            Return SavedTree
        End Function
        Private Function RebuildTree(ByVal savedTree As String) As Node
            Dim n As Node
            While Len(savedTree) > 0
                If savedTree.StartsWith("!") Then
                    CropString(savedTree)
                    n = New Node(NodeType.Leaf)
                    n.Value = CropString(savedTree)
                    Stack.Push(n)
                End If
                If savedTree.StartsWith("?") Then
                    CropString(savedTree)
                    n = New Node(NodeType.Branch)
                    n.RightChild = Stack.Pop
                    n.LeftChild = Stack.Pop
                    n.LeftChild.Parent = n
                    n.RightChild.Parent = n
                    Stack.Push(n)
                End If
            End While
            Return Stack.Pop
        End Function
        Private Function CropString(byRef cropMe as String) As String
            Dim L As String
            L = cropMe.Substring(0, 1)
            cropMe = cropMe.Substring(1)
            Return L
        End FunctionCropString just crops off and returns the first character of the string.. I'm going to rewrite this whole thing, but right now I'm just pleased I figured out how to make it work :)
    Cheers!

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

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

  • How to pretty print XML alerts

    Hi!
    I'd like to generate mail alerts in OSB which include a XML content. I need XML to be human friendly printed (that is with indentation) but XML is printed in a single line.
    Is there any way to pretty print XML content in alerts (and also in alerts emails).
    Thank you in advance.

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

  • Is there better way to do this?  (Xml Pretty Print | node removing)

    Hi all, I have been working at home on a small project to help my Java Jedi training. :-)
    My app saves quotes from authors in an xml file.
    I have a class [XmlRepository extends Thread] that holds control of an xml file to handle requests for Nodes.
    When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.
    Pretty print or correct Node removing.
    part of my xml is like this (I have resumed it for readability):
        <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
            <quotes/>
            <authors>
                <author id="f156c570-c676-4d69-9b15-ae7d859ff771" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Poe</lastNames>
                    <firstNames>Edgar Allan</firstNames>
                </author>
                <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Wilde</lastNames>
                    <firstNames>Oscar</firstNames>
                </author>
                <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Christie</lastNames>
                    <firstNames>Agatha</firstNames>
                </author>
                <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Shakespeare</lastNames>
                    <firstNames>William</firstNames>
                </author>
            </authors>
        </entities>If I remove A Node ( Edgar Allan Poe (1st in this case)) the resulting Xml when saved is like this (I have added the space indentation just as it is outputted by my code):
        <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
            <quotes/>
                <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Wilde</lastNames>
                    <firstNames>Oscar</firstNames>
                </author>
                <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Christie</lastNames>
                    <firstNames>Agatha</firstNames>
                </author>
                <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                    <lastNames>Shakespeare</lastNames>
                    <firstNames>William</firstNames>
                </author>
            </authors>
        </entities>this is how I initialize the XML DOM Handlers, and the method for removing a Node:
         * Initializes factory instances and member variables.
        private void initialize() {
            //obtain an instance of a documentFactory create a document documentBuilder
            this.documentFactory = DocumentBuilderFactory.newInstance();
            //Configure the documentFactory to be name-space aware and validate trough an xsd file
            this.documentFactory.setNamespaceAware(true);
            this.documentFactory.setValidating(true);
            this.documentFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            try {
                //obtain an instance of an XPathFactory
                this.xpathFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
                //obtain an instance of the xpath evaluator object
                this.xpathEvaluator = this.xpathFactory.newXPath();
                //set namespace mapping configurations
                NamespaceContextMap namespaceMappings = new NamespaceContextMap();
                namespaceMappings.put("xml", "http://www.w3.org/XML/1998/namespace");
                namespaceMappings.put("xmlns", "http://www.w3.org/2000/xmlns/");
                namespaceMappings.put("xsd", "http://www.w3.org/2001/XMLSchema");
                namespaceMappings.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                namespaceMappings.put(this.schemaNamespaceMapping, this.schemaNamespace);
                //add mappings
                this.xpathEvaluator.setNamespaceContext(namespaceMappings);
            } catch (XPathFactoryConfigurationException ex) {
                Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, ex);
            try {
                //obtain a trasformer factory to save the file
                this.transformerFactory = TransformerFactory.newInstance();
                this.transformerFactory.setAttribute("indent-number", 4);
                //obtain the transforme
                this.transformer = this.transformerFactory.newTransformer();
                //setup transformer
                this.transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                this.transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                this.transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text");
                this.transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            } catch (TransformerConfigurationException tcex) {
                Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, tcex);
         * Removes a node by evaluating the XPATH expression.
         * @param xpath A String instance with the XPATH expression representing the element to remove.
         * @throws com.fdt.cognoscere.storage.exceptions.UnableToRemoveException When an exception occurs that prevents the repository to execute the remove statement.
        public void removeNode(final String xpath) throws UnableToRemoveException {
            Node nodeToRemove = null;
            Node parentNode = null;
            //verify xpath
            if (xpath == null)
                throw new IllegalArgumentException("The xpath argument cannot be null.");
            //verify that the repository is loaded
            if (!this.loaded)
                throw new IllegalStateException("The XmlRepository faild to load properly and it is in an invalid state. It cannot perfom any operation.");
            try {
                //get the node to remove out of the xpath expression
                nodeToRemove = this.getNode(xpath);
                //throw an exception if no node was found to remove
                if (nodeToRemove == null)
                    throw new UnableToFindException("The node element trying to be remove does not exist.");
                //obtain the parent node to remove its child
                parentNode = nodeToRemove.getParentNode();
                //remove the node from the parent node
                nodeToRemove = parentNode.removeChild(nodeToRemove);
            } catch.......removed to save space{
            } finally {
                //normalize document
                this.document.normalize();
        }Please tell me if I could do this better,
    thanks,
    f(t)

    franciscodiaztrepat wrote:
    When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.Replaced? No, there's already a new-line character after the node that was removed. And there was one before that node too. You didn't remove either of those, so after the removal there are two consecutive new-line characters. As you can see.
    And no, trying to pretty-print the XML document won't remove any of those. It might add whitespace to make the document nicely indented, but it won't ever remove whitespace. If you want whitespace removed then you'll have to do it yourself.
    For example, after you remove a node, also remove the node following it if it's a whitespace text node. Or something like that.

Maybe you are looking for