Binary Tree Help

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

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

Similar Messages

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

  • Help loading a binary tree from file

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

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

  • Problem with binary tree please help

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

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

  • Help with a binary tree

    I'm writing a binary tree class and am having some trouble with the Insert function. Here is the code for the TreeNode class...
    public class TreeNode
         TreeNode Left;
         TreeNode Right;
         String Name;
         public TreeNode(String NodeName)
              Left = null;
              Right = null;
              Name = NodeName;
    }And this is the code for the Tree class...
    public class Tree
         TreeNode Root;
         public Tree(String RootNode)
              Root = new TreeNode(RootNode);
         public void Insert(String Name)
              InsertNode(Root, Name);
         public void InsertNode(TreeNode t, String NodeName)
              if (t == null)
                   t = new TreeNode(NodeName);
              else
                   if (NodeName.compareTo(t.Name) < 0)
                        InsertNode(t.Left, NodeName);
                   else if (NodeName.compareTo(t.Name) > 0)
                        InsertNode(t.Right, NodeName);
                   else if (NodeName.compareTo(t.Name) == 0)
                        System.out.println("Entered node that was already in Tree");
    }When I enter a new node into a Tree containing just the root, it follows the recursion through once, then creates the new TreeNode as it should. However, the new node is not really recognized by the tree because when I try to insert another node, it only finds the root in the tree and only goes through one recursion. What's wrong?

    I believe t.Left (or t.Right) is getting set in the line
    t = new TreeNode(NodeName);
    Since it is a recursive function, when it is called the second time, the "t" that is passed in is actually the original t.left (I think), which is getting set then.

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

  • Having trouble finding the height of a Binary Tree

    Hi, I have an ADT class called DigitalTree that uses Nodes to form a binary tree; each subtree only has two children at most. Each node has a "key" that is just a long value and is placed in the correct position on the tree determined by its binary values. For the height, I'm having trouble getting an accurate height. With the data I'm using, I should get a height of 5 (I use an array of 9 values/nodes, in a form that creates a longest path of 5. The data I use is int[] ar = {75, 37, 13, 70, 75, 90, 15, 13, 2, 58, 24} ). Here is my code for the whole tree. If someone could provide some tips or clues to help me obtain the right height value, or if you see anything wrong with my code, it would be greatly aprpeciated. Thanks!
    public class DigitalTree<E> implements Copyable
       private Node root;
       private int size;
       public DigitalTree()
           root = null;
           size = 0;
       public boolean add(long k)
           if(!contains(k))
                if(this.size == 0)
                    root = new Node(k);
                    size++;
                    System.out.println(size + " " + k);
                else
                    String bits = Long.toBinaryString(k);
                    //System.out.println(bits);
                    return add(k, bits, bits.length(), root);
                return true;
           else
               return false;
       private boolean add(long k, String bits, int index, Node parent)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(lsb == 0)
               if(parent.left == null)
                   parent.left = new Node(k);
                   size++;
                   //System.out.println(size + " " + k);
                   return true;
               else
                   return add(k, bits, index-1, parent.left);
           else
               if(parent.right == null)
                   parent.right = new Node(k);
                   size++;
                   //System.out.println(size + " " + k);
                   return true;
               else
                   return add(k, bits, index-1,  parent.right);
       public int height()
           int leftHeight = 0, rightHeight = 0;
           return getHeight(root, leftHeight, rightHeight);
       private int getHeight(Node currentNode, int leftHeight, int rightHeight)
           if(currentNode == null)
               return 0;
           //else
           //    return 1 + Math.max(getHeight(currentNode.right), getHeight(currentNode.left));
           if(currentNode.left == null)
               leftHeight = 0;
           else
               leftHeight = getHeight(currentNode.left, leftHeight, rightHeight);
           if(currentNode.right == null)
               return 1 + leftHeight;
           return 1 + Math.max(leftHeight, getHeight(currentNode.right, leftHeight, rightHeight));
       public int size()
           return size;
       public boolean contains(long k)
            String bits = Long.toBinaryString(k);
            return contains(k, root, bits, bits.length());
       private boolean contains(long k, Node currentNode, String bits, int index)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(currentNode == null)
               return false;
           else if(currentNode.key == k)
               return true;
           else
               if(lsb == 0)
                   return contains(k, currentNode.left, bits, index-1);
               else
                   return contains(k, currentNode.right, bits, index-1);
       public Node locate(long k)
            if(contains(k))
                String bits = Long.toBinaryString(k);
                return locate(k, root, bits, bits.length());
            else
                return null;
       private Node locate(long k, Node currentNode, String bits, int index)
           int lsb;
           try
               lsb = Integer.parseInt(bits.substring(index, index - 1));
           catch(StringIndexOutOfBoundsException e)
               lsb = 0;
           if(currentNode.key == k)
               return currentNode;
           else
               if(lsb == 0)
                   return locate(k, currentNode.left, bits, index-1);
               else
                   return locate(k, currentNode.right, bits, index-1);
       public Object clone()
           DigitalTree<E> treeClone = null;
           try
               treeClone = (DigitalTree<E>)super.clone();
           catch(CloneNotSupportedException e)
               throw new Error(e.toString());
           cloneNodes(treeClone, root, treeClone.root);
           return treeClone;
       private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
           if(treeClone.size == 0)
               cloneNode = null;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
           else if(currentNode != null)
               cloneNode = currentNode;
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
       public void printTree()
           System.out.println("Tree");
       private class Node<E>
          private long key;
          private E data;
          private Node left;
          private Node right;
          public Node(long k)
             key = k;
             data = null;
             left = null;
             right = null;
          public Node(long k, E d)
             key = k;
             data = d;
             left = null;
             right = null;
          public String toString()
             return "" + key;
    }

    You were on the right track with the part you commented out; first define a few things:
    1) the height of an empty tree is nul (0);
    2) the height of a tree is one more than the maximum of the heights of the left and right sub-trees.
    This translates to Java as a recursive function like this:
    int getHeight(Node node) {
       if (node == null) // definition #1
          return 0;   
       else // definition #2
          return 1+Math.max(getHeight(node.left), getHeight(node.right));
    }kind regards,
    Jos

  • Searching for a certain  binary tree from another tree........

    I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
    Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
    Tree B has a similar structure.
    The node used for both A and B.
    Node{
    Node left;
    Node right;
    My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
    So, the method should look like:
    public Node search(Node rootOfA, Node rootOfB){
    I know a simple recursive fuction can do the job. The question is all about the effciency....
    I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
    Anyone knows of that? Any friend can give a sound solution?
    Thank you all in advance.
    Jason
    Message was edited by:
    since81

    I'm not too sure if this would help but there goes.
    I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
    Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.
    :)

  • Binary Tree in Java - ******URGENT********

    HI,
    i want to represent a binary tree in java. is there any way of doing that.
    thanx
    sraphson

    HI,
    i want to represent a binary tree in java. is there
    e any way of doing that.
    thanx
    sraphsonFirst, what is a binary tree? Do you know how the binary tree looks like on puesdo code? How about a representation in terms of numbers? What is a tree? What is binary? The reason I ask is, what do you know about programming?
    Asking to represent a binary tree in java seems like a question who doesn't know how it looks like in the first please. Believe me, I am one of them. I am not at this level yet. If you are taking a class that is teaching binary trees and you don't know how it looks like, go back to your notes.
    Sounds harsh, but it is better to hear it from a person that doesn't know either then a boss that hired you because Computer Science was what you degree said. Yet, you don't know how to program?
    Telling you will not help you learn. I can show you tutorials of trees would be start on where to learn.
    HOW TO USE TREES (oops this is too simple, but it is a good example)
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    CS312 Data Structures and Analysis of Algorithms
    (Here is a course about trees. Search and learn)
    http://www.calstatela.edu/faculty/jmiller6/cs312-winter2003/index.htm

  • How to design  databse for binary tree

    kindly help in desiging databse for binary tree and also to retrive data from database.

    Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.

  • Binary Tree search and print methods

    Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
    public class TreeNode 
          public static String empName = null;
          public static int empNumber;
          public static String nextRec = null;
              TreeNode left;
          String Name;
          int Number;
          TreeNode right;
          public static void main(String[] args)
             VRead in = new VRead();
             VWrite out = new VWrite();
             System.out.println("Enter Choice: ");
             System.out.println("A: Enter Employee Information.");
             System.out.println("B: Search For Employee.");
             System.out.println("C: Print Entire Tree.");
             System.out.println("D: Exit.");
             System.out.println("_______________________________");
             char command = in.readChar();
             System.out.println();
             switch (command)
                case 'A':
                case 'a':
                   inputInfo(in, out);           
                   break;
                case 'B':
                case 'b':
                   break;
                case 'C':
                case 'c':
                   break;
                case 'D':
                case 'd':
                   System.exit(0);
                   break;
          public static void inputInfo(VRead in, VWrite out)
             out.write("Enter Employee Name: ");
             empName = in.readString();
             out.write("Enter Employee Number: ");
             empNumber = in.readInt();
             System.out.println();
             System.out.println();
             System.out.println("Enter Choice: ");
             System.out.println("A: Enter Employee Information.");
             System.out.println("B: Search For Employee.");
             System.out.println("C: Print Entire Tree.");
             System.out.println("D: Exit.");
             System.out.println("_______________________________");
             char command = in.readChar();
             System.out.println();
             switch (command)
                case 'A':
                case 'a':
                   inputInfo(in, out);           
                   break;
                case 'B':
                case 'b':
                   break;
                case 'C':
                case 'c':
                             break;
                case 'D':
                case 'd':
                   System.exit(0);
                   break;
          public TreeNode(String empName, int empNumber)
             Name = empName;
             Number = empNumber;
             left = null;
             right = null;
          public class Tree
             TreeNode Root;
             public void Tree(String RootNode)   
        // Errors come from next line
                  Root = new TreeNode(RootNode, Name, Number);   
             public void Insert(String Name, int Number)
                InsertNode(Root, Name, Number);
             public void InsertNode(TreeNode t, String empName, int empNumber)
                if (t == null)
                   t = new TreeNode(empName, empNumber);
                else
                   if (empName.compareTo(t.Name) < 0)
                      InsertNode(t.left, empName, empNumber);
                   else if (empName.compareTo(t.Name) > 0)
                      InsertNode(t.right, empName, empNumber);
                   else if (empName.compareTo(t.Name) == 0)
                      System.out.println("Entered node that was already in Tree");
       }im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method too

    Just having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
    As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
    FWIW
    I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
    *Before anyone flames, it's a joke
    G

  • 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

  • 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

  • Getting the height of a binary tree

    So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
    I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
    public int getHeight()
              int height;
              height = getHeightRecur(root);
              return height;
         public int getHeightRecur(BinTreeNode node)
              int theight;
              if(node == null)
                   theight = 0;
              else
                   theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
              return theight;
         private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              if(y>x)
                   result = y;
              return result;
         }

    j2ee_ubuntu wrote:
    it may help at some extent..
    private int getMax(int x, int y)
              int result = 0;
              if(x>y)
                   result = x;
              else if(y>x)
                   result = y;
    else //when both are equal
    result =x; OR result = y;//You can use one of them
              return result;
         }Edited by: j2ee_ubuntu on Nov 6, 2008 12:30 AMWhy not just use [ Math.max|http://java.sun.com/javase/6/docs/api/java/lang/Math.html#max(int,%20int)] or write
    public static int max(int a, int b) {
        return (a >= b) ? a : b;
    }

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

Maybe you are looking for