Tree Traversals

Hi i need some help on the following code. I'm doing tree traversals (inorder, preorder postorder) and everything works great except i can't get my program to get input from a file. Instead i have the following:
public class TreeTrav
     private TextReader my_input;
     private SampleQueue my_q;
     public static void main(String[] args)
          TreeNode root = new TreeNode("*");
          TreeNode left = new TreeNode("+");
          TreeNode right = new TreeNode("4");
          root.left = left;
          root.right = right;
          root.left.left = new TreeNode("2");
          root.left.right = new TreeNode("3");
          printInOrder(root);
          System.out.println();
          printPreOrder(root);
          System.out.println();
          printPostOrder(root);
          System.out.println();
     private static void printInOrder(TreeNode root)
          // inorder: <left> <root> <right>
          if(root != null)
               printInOrder(root.left);
               System.out.print(root.data + " ");
               printInOrder(root.right);
     private static void printPreOrder(TreeNode root)
          // preorder: <root> <left> <right>
          if(root != null)
               System.out.print(root.data + " ");
               printPreOrder(root.left);
               printPreOrder(root.right);
     private static void printPostOrder(TreeNode root)
          // postorder: <left> <right> <root>
          if(root != null)
               printPostOrder(root.left);
               printPostOrder(root.right);
               System.out.print(root.data + " ");
=========================================================
import java.util.*;
class SampleQueue
     private ArrayList my_data;
     public SampleQueue()
          my_data = new ArrayList();
     public void enqueue(Object val)
          my_data.add(val);
     // public void dequeue()
     public Object dequeue()
          return my_data.remove(0);
     public Object peek()
          if(isEmpty())
               return null;
          else
               return my_data.get(0);
     public boolean isEmpty()
          return my_data.size() == 0;
========================================================
public class TreeNode
     public Object data;
     public TreeNode left;
     public TreeNode right;
     public TreeNode(Object d)
          this(d, null, null);
     public TreeNode(Object d, TreeNode leftLink, TreeNode rightLink)
          data = d;
          left = leftLink;
          right = rightLink;
=========================================================
So how can i get infix expressions from an input.txt file and also how can i evaluate the expression. For instance if the input.txt file contains ( 2 + 3 ) * 4 i want to get :
2 +3 * 4 (in)
* + 2 3 4 (pre)
2 3 + 4 * (post)
20 (evaluate)
Thank you very much.
I

So your title is Tree Traversals and your unformatted code is (as near as I can tell) something to do with a tree data structure. But when we scan down past that to the very bottom, it appears that your real question is nothing to do with traversing a tree at all. It's about parsing an input string. Is that right? Have I understood your problem determination skills correctly?

Similar Messages

  • Please offer help on indexing a textbook

    I really need help on an assignment. It is supposed to create an index for a textbook and it has to be implemnted using trees.
    Generate an index for a book.
    The Input:
    The input file is specified as a command-line argument (use args). Be certain to check the validity of the file.
    The input file consists of a set of index entries. Each line consists of the string IX:, followed by an index entry name enclosed in braces, followed by a page number that is enclosed in braces. Each ! in an index entry name represets a sub-level. A |( represents the start of a range and a |) represents the end of the range. Occasionally, this will be the same page, and in that case, only output a single page number. Otherwise, do not collapse or expand ranges on your own. As an example, here's a sample input:
    IX: Series {2}
    IX: {Series!geometric|(} {4}
    IX: {Euler's constant} {4}
    IX: {Series!geometric|)} {4}
    IX: {Series!arithmetic|(} {4}
    IX: {Series!arithmetic|)} {5}
    IX: {Series!harmonic|(} {5}
    IX: {Euler's constant} {5}
    IX: {Series!harmonic|)} {5}
    IX: Series {5}
    The corresponding output is:
    Euler's constant: 4, 5
    Series: 2-5
    arithmetic: 4-5
    geometric: 4
    harmonic: 5
    (1)You must construct a general tree with a root node(the value stored in the root node will just be the word INDEX which should be the first item printed out - this is in addition to the output specification in the text) and its children consisting of top-level index terms, the next level of children consisting of sub -level index terms and so on;
    (2)Each node(except the root) must store the index term and page ranges;
    (3)In the general tree implementation the siblings need to be stored in a certain way so that a certain tree traversal algorithm will print out the index in the correct way.
       import java.io.*;          
    // BinaryTree class; stores a binary tree.
    // CONSTRUCTION: with (a) no parameters or (b) an object to
    //    be placed in the root of a one-element tree.
    // *******************PUBLIC OPERATIONS**********************
    // Various tree traversals, size, height, isEmpty, makeEmpty.
    // Also, the following tricky method:
    // void merge( Object root, BinaryTree t1, BinaryTree t2 )
    //                        --> Construct a new tree
    // *******************ERRORS*********************************
    // Error message printed for illegal merges.
    * BinaryTree class that illustrates the calling of
    * BinaryNode recursive routines and merge.
        public class BinaryTree //extends BinaryNode
          BinaryNode name = new BinaryNode();
           public static void main(String []args)
             String denem = "flag";
             BinaryTree index = new BinaryTree(denem);
             BinaryTree.insert(denem);
             System.out.println(index.infix(denem));
             System.exit(0);
           public BinaryTree( )
             name = null;
           public BinaryTree( String rootItem )
             BinaryNode name = new BinaryNode( rootItem, null, null );
           public void printInOrder( )
             //if( root != null )
             name.printInOrder( );
           public BinaryNode insert(String str, BinaryNode t)
             if(t == null)
                t = new BinaryNode(str, null, null);
             else if(str.compareTo(t.root) < 0)
                t.left = insert(str, t.left);
             else if(str.compareTo(t.root) > 0)
                t.right = insert(str, t.right);     
             return t;
           public BinaryNode insert(String str)
             BinaryNode n = root;
             return insert(str, n);
          // allows the pages to be printed out
           public String toString()
             String concat = name.getRoot();  
             return concat;
           public static void infix(BinaryNode t)     
             if (t != null)
                System.out.print("(");
                infix(t.getLeft());
                System.out.print(t);
                infix(t.getRight());
                System.out.print(")");
       // Class binary node
        final class BinaryNode
          protected String root;    //the name
          protected BinaryNode left;
          protected BinaryNode right;
          //protected String pages;
           public BinaryNode( )
             this( null, null, null); //, null);
           public BinaryNode( String root, BinaryNode left, BinaryNode right) //, String pages )
             root    = this.root;
             left    = this.left;
             right   = this.right;
           //  pages   = this.pages;
          * Return the size of the binary tree rooted at t.
           public static int size( BinaryNode t )
             if( t == null )
                return 0;
             else
                return 1 + size( t.left ) + size( t.right );
          * Return the height of the binary tree rooted at t.
           public static int height( BinaryNode t )
             if( t == null )
                return -1;
             else
                return 1 + Math.max( height( t.left ), height( t.right ) );
          // Print tree rooted at current node using inorder traversal.
           public void printInOrder( )
             if( left != null )
                left.printInOrder( );            // Left
             System.out.println( root );       // Node
             if( right != null )
                right.printInOrder( );          // Right         
           public String getRoot( )
             return root;
           public BinaryNode getLeft( )
             return left;
           public BinaryNode getRight( )
             return right;
           /*public void setElement( Object x )
             element = x;
           public void setLeft( BinaryNode t )
             left = t;
           public void setRight( BinaryNode t )
             right = t;
       } // end of class node
    This is the solution done using linked lists and treemap.
       import java.io.*;                         // to read the file
      A red-black tree is a binary search tree where every node has two children or is a leaf.
      It ensures O(log N) search times, at a cost of a more complicated insertion (and deletion)
      process. In a red-black tree, every node is colored either red or black, with a black root
      node, though a black root node isn't a requirement. In addition, if a node is red, its
      children must be black and every path from root to leaf (or null child node) must
      contain the same number of black nodes. These rules allow balancing
       import java.util.TreeMap;
       import java.util.Comparator;
       import java.util.StringTokenizer;
       public interface Iterator An iterator over a collection. Iterator takes the place of
       Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
       Iterators allow the caller to remove elements from the underlying collection during the iteration
       with well-defined semantics.
       import java.util.Iterator;
       import java.util.LinkedList;
       import java.util.ArrayList;
        public class IndexGenerator3
          private static final String START    = "|(";
          private static final String END      = "|)";
          private static final String SUBTOPIC = "!";
          private static final char SUBTOP= SUBTOPIC.charAt(0);
            private static final String INPUT = "hw3.in";     
          //private static final String INPUT = "input.txt";
           private static class Section
             public String name;
             public int start = -1;
             public int end = -1;
             //public int page;
        private LinkedList pages = new LinkedList();
             //constructor
              public Section(String name, int start, int end, int page)
                this.name = name;
                this.start = start;
                this.end = end;
                if(page >= 0) //this is for error checking
                   addPage(page);
              public void addPage(int page)
                pages.add(new Integer(page));
              public boolean isValid()
                return (start >= 0 && end >= 0 && pages.size() == 0) || pages.size() > 0;
          // allows the pages to be printed out
              public String toString()
                String concat = "";
                String szName = name;
                while(name.indexOf(SUBTOPIC) >= 0)      // returns tbe index of the first occurrence of the character. it takes a string or character as input parameter
                   concat += " ";
                   name = name.substring(name.indexOf(SUBTOPIC) +1);
                } //end of while
                concat += name + ": ";
                if (start >= 0)
                   concat += String.valueOf(start);
                   if (end >= 0 && end != start)
                      concat += "-" +end;
                else if (end >= 0)
                   concat += String.valueOf(end);
                else
                   Iterator iterator = pages.iterator();
                   while (iterator.hasNext())
                      concat += iterator.next() + ", ";
                   if (end < concat.length())
                      concat= concat.substring(0, concat.length()-2);
                return concat;
           public static void main(String[] args)
             try
                FileReader fr = new FileReader(INPUT);
                BufferedReader inFile = new BufferedReader(fr);
                TreeMap map = new TreeMap(
                       new Comparator()
                          public int compare(Object o1, Object o2)
                            String s1= (String) o1;
                            String s2= (String) o2;
                            s1.replace(SUBTOP, ' ');
                            s2.replace(SUBTOP, ' ');
                            s1.toLowerCase();
                            s2.toLowerCase();
                            return s1.compareTo(s2);
                            //return s1.compareToIgnoreCase(s2);     //Compares two strings lexicographically, ignoring case considerations.
                          public boolean equals(Object obj)
                            return false;
                String line = null;
                for (int i = 0; (line = inFile.readLine()) != null; i++)
                   StringTokenizer st = new StringTokenizer(line, "{}");
                   //if (st.countTokens() != 4)
                      //System.err.println("Error, Please correct: '" +line +"'");
                      //continue;
                   st.nextToken();
                   String name= st.nextToken();
                   st.nextToken();
                   String szPage= st.nextToken();
                   int start= -1;
                   int end= -1;
                   int page= -1;
                   if (name.endsWith(START))
                      name= name.substring(0, name.length() -START.length());
                      start= Integer.parseInt(szPage);
                   else if (name.endsWith(END))  //string built in function endsWith()
                      name= name.substring(0, name.length() - END.length());
                      end= Integer.parseInt(szPage);
                   else
                      page = Integer.parseInt(szPage); //convet the string into integers
                   Section section = (Section) map.get(name); //???????????
                   if (section == null)    //if object section is null, create new section object and initialize
                      section = new Section(name, start, end, page); //start cannot be omitted
                      map.put(name, section);
                   else if (start >= 0)   //if more pages under
                      section.start= start;
                   else if (end >= 0)   //if more pages under same heading are found
                      section.end = end;  // overwrite ???
                   else if (page >= 0)     //if there are more pages under the same heading add a page. euler s constant
                      section.addPage(page);
                fr.close();                //close the input stream
                System.out.println("\nIndex:");
                ArrayList invalid= new ArrayList(); // prevents marginal occurences of repetitive header lines
                Iterator sections= map.values().iterator();
                while (sections.hasNext())
                   Section section= (Section) sections.next();
                   if (section.isValid())
                      System.out.println(" " + section);
                   else
                      invalid.add(section);
                 catch(FileNotFoundException exception)
                { System.err.println("File not found"); }
                 catch (IOException exception)
                { System.out.println(exception); }
          }// end of main
       //     public void
       }  // end of class index generator
       I'm even offering the buy the program to make it more proffessional...the payment is as much duke dollars as i can give...We can also negotiate on e bay using real dollars, but the assignemtn is due tonite and i don t have much time... If someone will most kindly take a look, i will be greatly indebted and humbled...isn t there anyone on this site who actually loves solving this kinda stuff?

    actually, your solution was how I found about this forum. go to google,
    type in "index a textbook" + java, the forum pops up. Your solution has helped me a lot, I based my assignment on yours, just look at my main file. The difference was, I had to use a tree. That was more confusing than a linked list.

  • N-ary Trees non-recursive traversal algorithms

    Hi,
    Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
    or threading to climb back up the tree.
    Here's my attempt that seems to work but I would value so critical evaluation
    * An extension of the CommonAST that records the line and column
    * number.  The idea was taken from <a target="_top"
    * href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
    * FAQ: How can I include line numbers in automatically generated
    * ASTs?</a>.
    * @author Oliver Burn
    * @author lkuehne
    * @version 1.0
    * @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
    public class DetailAST
        public AST getFirstChild()
        public AST getNextSibling()
        public int getChildCount()
        public DetailAST getParent()
        public int getChildCount(int aType)
        public String getText()
    }This was cut back just to give you enough info
         public static AST getLeftMostChild(DetailAST ast) {
              DetailAST tempAst = ast.getFirstChild();
              while (tempAst.getFirstChild() != null) {
                   tempAst = tempAst.getFirstChild();
              return tempAst;
         public static void traverseASTInOrder(DetailAST root) {
              DetailAST current = getLeftMostChild(ast);
              processNode(current);
              while (current != root) {
                   if (current == current.getParent().getFirstChild()) {
                        processNode(current.getParent());
                   if (current.getNextSibling() != null) {
                        DetailAST sibling = current.getNextSibling();
                        if (sibling.getChildCount() != 0) {
                             current = (DetailAST) getLeftMostChild(sibling);
                             processNode(current);
                        } else {
                             current = sibling;
                             processNode(current);
                   } else {
                        current = current.getParent();
            // do stuff at inorder traversal
         public static void processNode(AST current) {
              System.out.println(current.getText());
         }for pre-order and post-order John Cowan put forward this algorithm
    http://lists.xml.org/archives/xml-dev/199811/msg00050.html
    traverse(Node node) {
        Node currentNode = node;
        while (currentNode != null) {
          visit(currentNode); //pre order
          // Move down to first child
          Node nextNode = currentNode.getFirstChild();
          if (nextNode != null) {
            currentNode = nextNode;
            continue;
          // No child nodes, so walk tree
          while (currentNode != null) {
            revisit(currentNode)     // post order
            // Move to sibling if possible.
            nextNode = currentNode.getNextSibling();
            if (nextNode != null) {
              currentNode = nextNode;
              break;
           // Move up
           if (currentNode = node)
          currentNode = null;
           else
          currentNode = currentNode.getParentNode();
      }Any comments, criticisms or suggestions ?
    regards
    David Scurrah

    Stack is recursion? As far as I know recursion is when
    function (method) calls itself. Just using some
    Collection, which java.util.Stack implements is not
    recursion.
    Regards
    PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
    In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
    My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
    public class Tree{
        public TreeIterator inOrderIteraror();
        public TreeIterator preOrderIterator();
    }Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
    Other than that, non-recursive algorithms are defnitely the way to go.

  • To display all the Nodes in a Binary Search Trees

    Hi,
    I want to traverse through all the nodes in a binary tree. I know that there are traversals like Preorder,Postorder,Inorder. But I am not able to write a recursive code for performing this operation. Can anyone please help me or give me an idea how to write a code to do any one of these traversal.
    Thanks a lot in advance.

    Hi,
    hmm .. how is a tree-node defined? - As so you have not posted a node-class, I will help you by demonstrating it for inOrder by normal language:
    The Idea is as follows:
    You have a root, that references to a tree-node. This tree-node has a value and 2 references to other tree-nodes, let's say they are named left and right. Because left an right are references to tree-nodes in the same way root is a reference to the tree-node, this fact can be used for recursive action on the tree.
    if you like to display all values in the tree, what do you have to do in a node?
    1. display the tree the left reference is pointing to
    2. display the value-Field
    3. display the tree the right reference is pointing to
    that is inOrder, assuming all lesser values are in the left tree and all greater are in the right tree.
    How to display the left and right trees?
    The same way you display this node, but this time you use the left / right reference as the node.
    So do it in pseudo-coding:
    void DisplayTree(NodeClass aNode) {
    if (aNode == null) return;
    DisplayTree(aNode.left);
    DisplayValue(aNode.value);
    DisplayTree(aNode.right);
    That is it - figure it out and try to write a program after this - good luck. To write one for pre-order and post-order should be easy if you have this one for inOrder.
    greetings Marsian

  • JTree traversals ??? pls help!

    My quaestion is:
    I have a graphical tree (JTree) in a swing window. My task is to
    display (by text) preorder and inorder traversals of the tree in a new bottom window (by splitting the main window).
    And I also have to add listeners to be able display the traversals when I make change in the tree. (I need to use DefaultMutableTreeNode)
    I've been trying to do it for two weeks. if you have any idea please help me...

    Hi.
    starting from the point where you have a JTree which uses Default..Nodes for its internal structure, your prob can be solved like this:public void showTraversing(JTree tree) [
      // assuming JTree is a tree with a data structure
      // using DefaultMutableTreeNode as its nodes
      TreeModel tmodel = tree.getModel();
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) tmodel.getRoot();
      // traverse them to the console:
      traversePreorder(node);
      traversePostordfer(node);
    // traverse recursivley in preorder
    public void traversePreorder(DefaultMutableTreeNode node) {
      if (node != null) {
        // preorder means node before children:
        System.out.println(node.toString() + " "); // or whatever you want to print
        // then process all children:
        Enumeration children = node.children();
        while (children.hasMoreElements()) {
          traversePreorder((DefaultMutableTreeNode) children.nextElement());
    // traverse recursivley in postorder
    public void traversePostorder(DefaultMutableTreeNode node) {
      if (node != null) {
        // postorder means process children first:
        Enumeration children = node.children();
        while (children.hasMoreElements()) {
          traversePreorder((DefaultMutableTreeNode) children.nextElement());
        // then the actual node:
        System.out.println(node.toString() + " "); // or whatever you want to print
    }I didn't test this code so I don't give any warranties that it works. But I'm pretty sure there are not too many bugs in there.
    Any questions? Shouldn't be that hard to reproduce.
    HTH & cheers,
    kelysar
    HTH,

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

  • Binary Tree Search

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

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

  • Constructing Binary tree

    So this is my first post here and i am beginning to like this forum.
    Can anybody help me on how to construct Binary tree from inorder and postorder traversals,i just want to know the algorithm so that i can apply it.
    Please help.

    I would like to pick a minor little nit with this analysis. The algorithm that has been proposed assumes that all the nodes are all distinct and that having selected the root from the end of the post-order listing that it is POSSIBLE to find it in the in-order list. What if you find multiple copies of this node?
    If multiple copies of the root are found, you must have a method to distinguish, which one is the proper dividing point. In the worst possible case, the problem can not be solved at all. For example suppose my post-order and my in-order lists were these:
    a a a a a
    a a a a a
    The shape of the tree is indeterminant in this case.
    If you allow different tree nodes to contain identical values your recursive algorithm needs some modification.
    The fix is this:
    1) allow your recursive algorithm to fail (and report back any success or failure)
    This can and happen if the two lists that you passed in are incompatible. For example they could have different nodes in them.
    2) when you pick the root off the end of the post order list, you search for it in the in-order list, you could find multiple matches or you could find no matches. You must explore each of these independently because each one could lead to a possible different solution, or could lead to no solution. Of course in the case of no matches, you must report back a failure.
    Depending on your needs, you can either stop the first time that you have successfully assembled a tree that matches the two supplied inputs, or you can have it grind on and have it enumerate all the possible tree arrangements that could have generated from the two traversals that you started with.
    It might help to visualize if you write out all the possible trees with just the three nodes AAB. There are 15 of them, 5 with B at the root, 5 with A at the root and B in the left and 5 with B in the right. It is easy to draw the trees and to immediately write both their in-order and their post-order traversals.
    Any traversal is just a list of the 3 nodes and there are 3 arrangements, AAB, ABA, and BAA. There are exactly 9 ordered pairs of these traversals so you can't get all 15 trees from the 9 pairs.
    Sho nuff, three ordered pairs are unambiguous and generate a single unique tree(e.g. in:BAA post:ABA) and six of them come from ambiguous pairs of trees (e.g. in:ABA post:ABA - you can't tell if this is a tree ABA all leaning to the left or all leaning to the right)
    Enjoy

  • Binary tree per levels

    I must make a method that takes the variable "item" and put it in a string, for each element of the binary tree, but per levels..for example:
                  1
       2     3               6
    5                                4must return this string: 1 , 2 , 3 , 6 , 5 , 4
    The tree is something like:
    public class BinTree{
          private Node root;
          public class Node{
                public Node left;
                public Node right;
                public int item;
    }Thank you very much :)

    Sorry, I didn't specify: I can use recursion,Level order traversals are normally performed using a queue.
    but in this case I don't know how to do it "per levels"..can
    someone help me? Sure: use a queue and try to do it first on a pice of paper.
    Also if you don't write the method,I won't. ; )
    What would you learn from that? Perhaps a little, but you'll learn far more by doing it yourself.
    just to tell me how to go through the tree in this
    case. ThanksHere's some pseudo code:
    LEVELORDER(root)
      queue.enqueue(root)
      WHILE queue not empty
        n = queue.dequeue()
        IF n.left  != null -> queue.enqueue(n.left )
        IF n.right != null -> queue.enqueue(n.right)
      END WHILE
    END LEVELORDERAnd an example. Take the following tree:     5
      3     8
    1   4 6   9No apply that pseudo code:
    queue = new queue
    queue.enqueue(5)
    while(queue is not empty) {
      n = queue.dequeue() = 5
      n.left  != null, so queue.enqueue(3)
      n.irght != null, so queue.enqueue(8)
      (queue is now [3,8])
      n = queue.dequeue() = 3
      n.left  != null, so queue.enqueue(1)
      n.irght != null, so queue.enqueue(4)
      (queue is now [8,1,4])
      n = queue.dequeue() = 8
      n.left  != null, so queue.enqueue(6)
      n.irght != null, so queue.enqueue(9)
      (queue is now [1,4,6,9])
      n = queue.dequeue() = 1
      n.left  == null
      n.irght == null
      (queue is now [4,6,9])
      n = queue.dequeue() = 4
      n.left  == null
      n.irght == null
      (queue is now [6,9])
      n = queue.dequeue() = 6
      n.left  == null
      n.irght == null
      (queue is now [9]) 
      n = queue.dequeue() = 9
      n.left  == null
      n.irght == null
      (queue is now [])
      queue is empty, end while.
    }As you can see, the items are dequeued in the following order: 5, 3, 8, 1, 4, 6, 9.
    Good luck.

  • Problem with trees and memory handling.

    Hi there, I just want to know if, when I create a large binary tree, and I re-"pointed" the root pointer to another node somewhere below in that same tree (say, a terminal node), will the "upper" parts of the tree (starting from the new root node) be removed/deleted from memory? Please explain your answers.
    Thank you.

    f I changed the root to B, will A and its children be
    deleted from memory?If you do root = B, AND if nothing else is referring to A or C or anything else beneath them, then A, C, and all of C's children will become eligible for garbage collection.
    Whether the memory actually gets cleaned up is something you can't really predict or control, but it doesn't really matter. If it's needed, it will get cleaned up. If it's not needed, it may or may not get cleaned up, but your program won't care.
    So, in short, yes, for all intents and purposes, A's, C's, and C's descendants' memory is released when you re-root to B.

  • How to blick tree view few specific nodes

    here i got a code which show how to blink tree view node but i am confuse that how to blink few node.
    Answered by:
    Avatar of Tamer Oz
    20,185
    Points
    Top 0.5
    Tamer Oz
    Partner Joined Sep 2009
    2
    8
    17
    Tamer Oz's threads
    Show activity
    Treeview control - How to make a node blink?
    Visual Studio Languages
    .NET Framework
    >
    Visual C#
    Question
    Alert me
    Question
    Vote as helpful
    0
    Vote
    Hi,
    Is there a "elegant" way to make blink a treeview node?
    I am thinking to use a timer with the collection of nodes that I want to make the blink effect, and update the icon ...
    Friday, November 06, 2009 6:19 PM
    Reply
    |
    Quote
    |
    Report as abuse
    Avatar of Kikeman
    Kikeman
    R. BOSCH
    105 Points
    All replies
    Question
    Vote as helpful
    0
    Vote
    Hi,
    You can develop your custom control for this purpose. The logic you mentioned was correct. Here is a sample control that I developed by the logic you mentioned.
    public class BlinkingTreeView : TreeView
    private Timer t = new Timer();
    private List<TreeNode> blinkingNodes = new List<TreeNode>();
    public BlinkingTreeView()
    t.Interval = 1000;
    t.Tick += new EventHandler(t_Tick);
    bool isNodeBlinked = false;
    void t_Tick(object sender, EventArgs e)
    foreach (TreeNode tn in blinkingNodes)
    if (isNodeBlinked)
    //update Icon
    tn.Text = tn.Text.Substring(0, tn.Text.Length - 1);//to test
    isNodeBlinked = false;
    else
    //update Icon
    tn.Text = tn.Text + "*";//to test
    isNodeBlinked = true;
    public void AddBlinkNode(TreeNode n)
    blinkingNodes.Add(n);
    public void RemoveBlinkNode(TreeNode n)
    blinkingNodes.Remove(n);
    public void ClearBlinkNodes()
    blinkingNodes.Clear();
    public List<TreeNode> BlinkingNodes
    get { return blinkingNodes; }
    public int BlinkInterval
    get { return t.Interval; }
    set { t.Interval = value; }
    public void StartBlinking()
    isNodeBlinked = false;
    t.Enabled = true;
    public void StopBlinking()
    t.Enabled = false;
    just show me how to use BlinkingTreeView class. i will have tree view which will have few node and few nodes may have few child nodes. now how to achieve by this class BlinkingTreeView and show me how to blink few specific node not all. thanks

    better to come with code. first populate tree view with some dummy node this way
    Root
           Child1
                    Child1-sub1
                    Child1-sub2
           Child2
                    Child2-sub1
                    Child2-sub2
    now blink Child1-sub2 & Child2-sub1. please come with code. thanks

  • Follow up Tree Question

    Hey,
    Using the arrows, when I open one tree node, I want other
    tree nodes to close. I saw a sample that sepiroth had done, but I
    don't want to click on the whole bar. I just want to use the arrows
    to expand and contract. Any help would be great. I have attached
    the code

    If you just wish to make a duplicate of one hard drive to another hard drive in the same G5, then do this:
    Clone using Restore Option of Disk Utility
    Open Disk Utility from the Utilities folder.
    Select the destination volume from the left side list.
    Click on the Restore tab in the DU main window.
    Check the box labeled Erase destination.
    Select the destination volume from the left side list and drag it to the Destination entry field.
    Select the source volume from the left side list and drag it to the Source entry field.
    Double-check you got it right, then click on the Restore button.
    Destination means the second internal drive. Source means the internal startup drive.

  • How can I display and change built-in symbols of a tree control programmatically?

    I want to set the built-in symbols of a tree control during runtime.
    I only found an example to assign custom pictures but not how to select one of the 40 built-in symbol.
    Many Thanks 
    Solved!
    Go to Solution.

    The ActiveItem.SymbolIndex will allow you to select the symbol for the active item. You can use the ListBox Symbol Ring Constant (Dialog and User Interface palette) to select a symbol (or you can just enter the number directly if you know what it is).
    Message Edited by smercurio_fc on 07-10-2008 09:36 AM
    Attachments:
    Example_VI_BD6.png ‏2 KB

  • How can I create a Tree with Color Picker icons?

    I'm a newbie to Flex. I want to create a tree which has color
    picker icons.
    As an analogy for the Mac users out there, I envision a
    control like the Calendars section in iCal, where you can specify
    the color for each individual node. These colors are then used in
    other parts of the application.
    The Flex 3 documentation specifies four methods for setting
    node icons on a Tree control, none of which seems to suit my needs:
    -The folderOpenIcon, folderClosedIcon, and defaultLeafIcon
    properties
    -Data provider node icon fields
    -The setItemIcon() method
    -The iconFunction property
    In other words, I want to "setItemIcon" to an mx:ColorPicker,
    if that makes any sense.
    Is there a standard way of doing this? If not, how can I go
    about implementing such a control? Thanks in advance!

    well, Network UI should be used.

  • To get  node value in a tree

    I have a tree with 3 level and it is working fine.. In view mode I need the First child value of the 3rd level with out clicking / Selecting from teh Tree node..
    for eg;
    A -- ist level
    Ap -- 2nd level
    Apple -- 3rd level
    So What I need is that I should get a message 'Apple' While landing teh Form itself without clicking on teh Tree
    Thanks in Advance...

    To my knowledge it is not possible to get the value of a node which is not selected.
    What you have to do is to build up a memory structure similar to your tree, then you can access any node at any time.
    Peter

Maybe you are looking for

  • How do I add a digital signature to my online form?

    With regular Adobe (Standard or Professional) software, you can add a digital signature line.  I want to know how I can do it on FormCentral. When I PDF the form I created on FormCentral and try to add the digital signature in Adobe, I get a message

  • How do I update a waveform chart with multiple plots one point at a time?

    Hi, I am updating multiple plots one point at a time.  That is, every time I update the chart I have a value for one of the plots.  If I put in a cluster with NaN for each of the charts except the one with the data I can only get individual points on

  • Download All-in-One HP Photosmart 3100 for windows 7 Home Premium

    Good Afternoon! Unfortunately I deleted my software All-in-One for my HP Photosmart C3100 printer. The problem is: When I try to instal the software All-in-one there is a conflict. When I bought my printer my system was Windows XP and now is Window 7

  • ST05 Trace on a select query on BSEG table

    hi all, this is my select query on table BSEG table:   SELECT bukrs          belnr          gjahr          buzei          KOART          mwskz          kostl          lifnr          aufnr          werks          ebeln          txjcd          projk FR

  • EOL clarification

       When looking at the eol notes for say a 3750G switch and it says  End of Vulnerability/Security Support: OS SW  , January 31,2016  .  Does this mean there will be no more IOS updates for this switch model after this date even for security holes or