Binary tree using inorder traversal algorithm

I need to draw a Binary tree using Inorder traversal algorithm.. in java applets using rectangles and ellipse objects.. can anyone help me about this ? I will be really thankful to yu

I think this is my psychic Sunday, so here's my attempt at answering
this vaguely stated question. First have a look at this fine piece of
ASCII art:--------------------------------------------   ^         ^
| A                    T                     |   |         |
|                                            |   |        root
---------L-----------------------R---------+   |         v
| B                    |  C                  |   |
|                      |                     |   |
|                      |                     | height
|                      |                     |   |
|                      |                     |   |
|                      |                     |   |
|                      |                     |   |
|                      |                     |   |
|                      |                     |   |
|                      |                     |   |
-------------------------------------------+   v
<--------------------width------------------->Suppose you have a rectangle 'width' wide and 'height' high. The root
of the tree can be drawn at position T and (if present), two lines can be
drawn to the positions L and R respectively. Now recursively call your
same method using the computed rectangle A and B for the left and
right subtrees L and R respectively.
kind regards,
Jos

Similar Messages

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

  • DefaultMutableTreeNode   inorder traversal ?

    Hi,
    I need to traverse a JTree using inorder traverse. any suggestion??? help pls.
    Inorder Traverse is visiting all nodes of tree from left to right.

    Hi.
    Inorder traversal will only work with binary trees since you don't know when to process the current node when you've got variating number of children. Let's say you've got a (binary) tree like this:
        1
      2   3
    4   5Then inorder would give you 4, 2, 5, 1, 3 - after the rule: first process the left child, then the root (the current node), then the right child.
    But what would it look like in case you've got a tree like that:
        1
       /|\
      2 3 4When would the '1' appear in the output? pre- and postorder will work fine becaue processing the curent node before or after the children is easy - but you don't know the position when to process it when using inorder traversal.
    Of course you could count the children and say that the 'middle' is between them - e.g. with five children, the root is to be processed after child #2 or #3 to be in the middle - but that'd be no inorder processing since that doesn't really exist for tree with variable children amounts.
    I might be the case that you know that your JTree will always have two or less children for each node - the you just have to process the current node after the first and before the second child. But when using DefaultMutableTreeNode you cannot be sure about this since that class allows any number of children.
    HTH, cheers
    kelysar

  • 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 inorder traversal without recursion

    Using Java, write a method that does an in-order traversal of a binary tree WITHOUT using recursion. based on the following code
    BTreeNode.java
    public class BTreeNode
    public BTreeNode LEFT;
    public BTreeNode RIGHT;
    public String VALUE;
    BTreeUtil.java
    public class BTreeUtil
    public static void listNodes(BTreeNode a_oRootNode)
    // insert code here...
    }

    This is definitely the wrong place to post this. Nevertheless you'll have to use a stack. While traversing down the tree you push the parents onto the stack.
    stephan

  • Any good algorithm to balanced a strict binary tree for a ordered set

    Hi,
    I have created a syntax tree of a binary operator that is associative but not commutative. The resultant is a unbalanced strict binary tree.
    I have tried using AVL tree as well as a heap. But they will occasionally destruct the non-commutative property of the syntax tree.
    Is there any efficient algorithm that I can used to balance this tree?
    Thank you.

    Is linear time good enough?
    1. Traverse your tree to build a list.
    2. Recursively turn the list into a tree. Pseudocode for this step: fun listToTree( [a] ) = Leaf(a)
      | listToTree( xs ) = Node( listToTree(firstHalf(xs)), listToTree(secondHalf(xs)) );

  • Non recursive preorder traversal of binary tree

    hi,
    I am trying to implement a non-recursive traversal of binary tree. I already know the recursive one.
    I am trying to do it by using a Stack.
    I begin by Pushing the root of an element on to a stack, and then run a while loop in which i pop an element of the stack and get its children from right to left. and push it in the same order on to the stack. So during the next iteration of my while loop the top most element gets popped and its children and pushed on to the stack in the above manner.
    but when i pop an element from a stack its popped as an object so i dont know how to access its children.
    help me i am really stuck.

    Hi, I suppose you have something like this :
    class Stack {
      public void push( Object object ) throws ... { ... }
      public Object pop() throws ... { ... }
    class Element {
      Element elem;
      stack.push(elem);
      /* because pop() method return an object of type Object
      ** if you are sure that your stack only contains Element object
      ** then you need to cast (change the type of) what the pop() method
      ** returns in this way :
      elem = (Element)stack.pop();
      ...further reading on casting will be a good idea anyway.

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

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

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

  • Traverse a binary tree from root to every branch

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

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

  • 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

  • Inorder traversal manipulating array

    I have an array of integers in main that I store into a binary search tree, I want to use my inorder traversal routine to store the values back into the array contained in main.
    Shouldn't I be able to refrence the array in main if I declare it as protected?
    I get an unresolved symbol error in NetBeans when I try this. What is the proper way.
    again Thanks for any help given.

    I have an array of integers in main that I store into
    a binary search tree, I want to use my inorder
    traversal routine to store the values back into the
    array contained in main.Just out of curiosity -- if you store these values back in the array again the way you intend to, you've
    effectively sorted the original array. Why not sort the array in the first place? You don't need that
    search tree at all ...
    kind regards,
    Jos

  • How to extend  breadth first Search for Binary Tree to any kind of Tree??

    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
    I have following code to successfully apply for breadth first Search in Binary Tree as follows,
    package a.border;
    import java.util.ArrayList;
    import java.util.LinkedList;
    public class Tree
        int root;
        Tree left;
        Tree right;
        static ArrayList<Integer> list = new ArrayList<Integer>();
        static ArrayList<Tree> treeList = new ArrayList<Tree>();
        private static LinkedList<Tree> queue = new LinkedList<Tree>();
         * @param root root value
         * @param left left node
         * @param right right node
        public Tree(int root, Tree left, Tree right)
            this.root = root;
            this.left = left;
            this.right = right;
        /** Creates a new instance of Tree
         * You really should know what this does...
         * @param root
        public Tree(int root)
            this.root = root;
            this.left = null;
            this.right = null;
         * Simply runs a basic left then right traversal.
        public void basicTraversal()
            //Check if we can go left
            if (left != null)
                left.basicTraversal();
            //Add the root
            list.add(root);
            //Check if we can go right
            if (right != null)
                right.basicTraversal();
        public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
            //Add the root to the arraylist, we know it is always the first entry.
            list.add(root);
            //Basically we add the first set of nodes into the queue for
            //traversing.
            //Query if left exists
            if (left != null)
                //Then add the node into the tree for traversing later
                queue.add(left);
            //Same for right
            if (right != null)
                queue.add(right);
            //Then we call the traverse method to do the rest of the work
            return traverse(list);
        private ArrayList<Integer> traverse(ArrayList<Integer> list)
            //Keep traversing until we run out of people
            while (!queue.isEmpty())
                Tree p = queue.remove();
                //Check if it has any subnodes
                if (p.left != null)
                    //Add the subnode to the back of the queue
                    queue.add(p.left);
                //Same for left
                if (p.right != null)
                    //Same here, no queue jumping!
                    queue.add(p.right);
                //Append to the ArrayList
                list.add(p.root);
            //And return
            return list;
         * Makes a tree and runs some operations
         * @param args
        public static void main(String[] args)
             *                             4
             *          t =           2       6
             *                      1   3    5   7
            Tree leaf6 = new Tree(1);
            Tree leaf7 = new Tree(3);
            Tree leaf8 = new Tree(5);
            Tree leaf9 = new Tree(7);
            Tree t4 = new Tree(2, leaf6, leaf7);
            Tree t5 = new Tree(6, leaf8, leaf9);
            Tree t = new Tree(4, t4, t5);
            t.basicTraversal();
            System.out.println("Here is basicTraversal ="+list.toString());
            list.clear();
            t.getBreadthTraversal(list);
            System.out.println("getBreadthTraversal= " +list.toString());
            list.clear();
        }Can Guru help how to update to any kind of tree??
    here this code is for the tree like:
             *                             4
             *          t =           2       6
             *                      1   3    5   7
             */But i hope the new code can handle tree like:
             *                             4
             *                           /   | \
             *                          /     |   \
             *          t =            2     8   6
             *                        / |  \    |    /| \
             *                      1 11  3 9   5 10  7
             */Thanks

    sunnymanman wrote:
    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
    What do all trees have in common? And what do all nodes in trees have in common?
    At least these things:
    interface Tree<T> {
        Node<T> getRoot();
    interface Node<T> {
        T getData();
        List<Node<T>> getChildren();
    }Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
    class BinaryTree<T extends Comparable<T>> implements Tree<T> {
        protected BTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class BTNode<T> implements Node<T> {
        private T data;
        private Node<T> left, right;
        public List<Node<T>> getChildren() {
            List<Node<T>> children = new ArrayList<Node<T>>();
            children.add(left);
            children.add(right);
            return children;
        public T getData() {
            return data;
    class NTree<T> implements Tree<T> {
        private NTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class NTNode<T> implements Node<T> {
        private T data;
        private List<Node<T>> children;
        public List<Node<T>> getChildren() {
            return children;
        public T getData() {
            return data;
    }Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
    interface Traverser<T> {
        List<Node<T>> traverse(T goal, Tree<T> tree);
    }And finally write an implementation for it:
    class BreathFirst<T> implements Traverser<T> {
        public List<Node<T>> traverse(T goal, Tree<T> tree) {
            Node<T> start = tree.getRoot();
            List<Node<T>> children = start.getChildren();
            // your algorithm here
            return null; // return your traversal
    }... which can be used to traverse any tree! Here's a small demo of how to use it:
    public class Test {
        public static void main(String[] args) {
            Tree<Integer> binTree = new BinaryTree<Integer>();
            // populate your binTree
            Tree<Integer> nTree = new NTree<Integer>();
            // populate your nTree
            Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
            // Look for integer 6 in binTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
            // Look for integer 6 in nTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
    }Good luck!

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

Maybe you are looking for

  • Help with creating a search box

    Lo, I am making a website using dreamweaver 8 and was wondering if anyone could help me in making a simple search box. If your wondering what i mean when i say search box, i mean a text field where you can enter a search subject and a button to submi

  • Why does my 16gb 6th generation ipod nano skip and stutter during playback?

    Why does my 16gb 6th generation ipod nano skip and stutter during playback?

  • Cost estimate currency

    Hello Gurus, Once the cost estimate is run for a material, we could see the values in controlling currency. But i need Company code currecny. Could any body let me know the configuration for this. Thanks in advance, SK

  • Default reset problem

    My wrt120n router will not reset or if it dose the pw:admin is not valid. I held down the reset botton for 5 sec., 10 sec., 30 sec., 1 min., & 2 min. and powered down for same amount of time, still not able to use pw:admin with username blank. So I'm

  • Some packeges need to be update

    These aren't marked in red: -cpio-2.7 -device-mapper-1.02.13 -klibc-1.4.30 -pcre-6.7 -psmisc-22.3 -reiserfsprogs-3.6.20 These are marked but not update yet: -autoconf-2.61 -bash-3.2 -db-4.5.20 -findutils-4.2.29 -gettext-0.16.1 -lvm2-2.2.02.15 -m4-1.4