Binary Tree Problem, help !!!!!!!

Hi I have some Tree Traversal problem,
my output has this problem,what's going on????
Exception in thread "main" java.lang.NullPointerException
at Tree.inTraversal2(Tree.java:150)
at TreeTest.main(TreeTest.java:33)
My Tree.java:
class TreeNode {
   TreeNode leftNode;          
   TreeNode rightNode;
   int data;
   public TreeNode(int nodeData)
      data = nodeData;             
      leftNode = rightNode = null;
   public void insert(int value)
      if( value < data )
         if( leftNode == null )
            leftNode = new TreeNode(value);
         else
            leftNode.insert(value);
      else if ( value > data )
         if( rightNode == null )
            rightNode = new TreeNode(value);
         else
            rightNode.insert(value);
   }  //end method insert
}  //end class TreeNode
public class Tree {
   TreeNode root;
   Stack s;
   public Tree()
      root = null;
   public void insertNode(int value)
      if( root == null )
         root = new TreeNode(value);
      else
         root.insert(value);
   public void inTraversal2(TreeNode node)
         if( node == null )
         return;
     TreeNode p;
     p = node;
     do
            while(p != null)
                 s.push(p); //problem comes in here
                 p = p.leftNode;
             if(!s.empty())
                 p = s.pop();
                 System.out.print( p.data + " " );
                 p = p.rightNode;
               }while( (p != null) || (!s.empty()));
}  //end class TreeMy Stack.java:
public class Stack {
      TreeNode items[];
     int StackSize;
     int top;
    public Stack(int size)
         StackSize = size;
        items = new TreeNode[size];
        top = -1;
    public boolean empty()
         if(top == -1)
           return true;
        else
          return false;
    public boolean full()
         if(top == StackSize-1)
           return true;
         else
           return false;
    public void push(TreeNode c)
        if(full() == true)
           System.out.println("stack overflow");
        else
            items[++top] = c;
    public TreeNode pop()
         if(empty())
           System.out.println("stack underflow");
        return items[top--];
}

You don't seem to instantiate Stack anywhere.

Similar Messages

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

  • Binary tree problems.

    hi everyone.
    I have an assignment to use a binary search tree whose nodes hold a reference to a string, and also to an int which is the count of how many times that word occurs in an input file, then it traverses the tree and prints out the result to an output file.
    But when I compile, I get this one error, which I'm not sure how to fix.
    the error says:
    WordCount2.java:142: displayNode(java.lang.String,int) in Node cannot be applied to () localRoot.displayNode();
    and here's he code:
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    import java.lang.String.*;
    class WordCount2
    public static void main (String [] args) throws IOException
    StringTokenizer tokenizer;
    String inputpath, outputpath;
    String line = "";
    String str = "";
    Tree tree = new Tree();
    int i = 0;
    int count = 0;
    Node now = new Node();
    BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the pathname of the input file: ");
    inputpath = stdin.readLine();
    System.out.println("Enter the pathname of the output file: ");
    outputpath = stdin.readLine();
    FileReader textFile1 = new FileReader(inputpath);
    BufferedReader inputFile = new BufferedReader (textFile1);
    FileWriter textFile2 = new FileWriter(outputpath);
    PrintWriter outputFile = new PrintWriter(textFile2);
    while ((line = inputFile.readLine()) != null)
    tokenizer = new StringTokenizer(line, " ");
    while (tokenizer.hasMoreTokens())
    String s = tokenizer.nextToken().toLowerCase();
    tree.insert(s, i);
    tree.inOrderTraverse(now);
    class Node
    public String sData;
    public int iData;
    public Node leftChild;
    public Node rightChild;
    public Node()
    sData = "";
    iData = 0;
    public void displayNode(String s, int i) throws IOException
    String file = "test1.txt";
    FileReader fr = new FileReader (file);
    BufferedReader inFile = new BufferedReader(fr);
    String line = inFile.readLine();
    String file2 = "outfile.txt";
    FileWriter fw = new FileWriter (file2);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);
    outFile.print (s);
    outFile.print (" - ");
    outFile.print (i);
    outFile.flush();
    class Tree
    private Node root;
    public Tree()
    root = null;
    public void insert(String sd, int id)
    Node newNode = new Node();
    newNode.sData = sd;
    newNode.iData = id;
    if (root == null)
    root = newNode;
    else
    Node current = root;
    Node parent;
    while (true)
    parent = current;
    if ((newNode.sData).compareTo(current.sData) < 0)
    current = current.leftChild;
    if (current == null)
    parent.leftChild = newNode;
    return;
    else if((newNode.sData).compareTo(current.sData) == 0)
    increment(newNode.iData);
    else
    current = current.rightChild;
    if(current == null)
    parent.rightChild = newNode;
    return;
    public void inOrderTraverse (Node localRoot)
    if (localRoot != null)
    inOrderTraverse(localRoot.leftChild);
    localRoot.displayNode();
    inOrderTraverse(localRoot.rightChild);
    private int increment(int i)
    return i++;
    any help is greatly appreciated! thanks!

    ok, thanks a lot!
    so i was able to fix that, and it compiles, but when I run it, it gets stuck after i enter the name of the input and output files. anyone have any idea why it's doing that? I can't figure it out...
    here's the edited code:
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    import java.lang.String.*;
    class WordCount2
    public static void main (String [] args) throws IOException
    StringTokenizer tokenizer;
    String inputpath, outputpath;
    String line = "";
    String str = "";
    Tree tree = new Tree();
    int i = 0;
    int count = 0;
    Node now = new Node();
    BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the pathname of the input file: ");
    inputpath = stdin.readLine();
    System.out.println("Enter the pathname of the output file: ");
    outputpath = stdin.readLine();
    FileReader textFile1 = new FileReader(inputpath);
    BufferedReader inputFile = new BufferedReader (textFile1);
    FileWriter textFile2 = new FileWriter(outputpath);
    PrintWriter outputFile = new PrintWriter(textFile2);
    while ((line = inputFile.readLine()) != null)
    tokenizer = new StringTokenizer(line, " ");
    while (tokenizer.hasMoreTokens())
    String s = tokenizer.nextToken().toLowerCase();
    tree.insert(s, i);
    tree.inOrderTraverse(now);
    class Node
    public String sData;
    public int iData;
    public Node leftChild;
    public Node rightChild;
    public Node()
    sData = "";
    iData = 0;
    public void displayNode(String s, int i) throws IOException
    String file = "test1.txt";
    FileReader fr = new FileReader (file);
    BufferedReader inFile = new BufferedReader(fr);
    String line = inFile.readLine();
    String file2 = "outfile.txt";
    FileWriter fw = new FileWriter (file2);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);
    outFile.print (s);
    outFile.print (" - ");
    outFile.print (i);
    outFile.flush();
    class Tree
    private Node root;
    public Tree()
    root = null;
    public void insert(String sd, int id)
    Node newNode = new Node();
    newNode.sData = sd;
    newNode.iData = id;
    if (root == null)
    root = newNode;
    else
    Node current = root;
    Node parent;
    while (true)
    parent = current;
    if ((newNode.sData).compareTo(current.sData) < 0)
    current = current.leftChild;
    if (current == null)
    parent.leftChild = newNode;
    return;
    else if((newNode.sData).compareTo(current.sData) == 0)
    increment(newNode.iData);
    else
    current = current.rightChild;
    if(current == null)
    parent.rightChild = newNode;
    return;
    public void inOrderTraverse (Node localRoot) throws IOException
    String s = "";
    int i = 0;
    if (localRoot != null)
    inOrderTraverse(localRoot.leftChild);
    localRoot.displayNode(s, i);
    inOrderTraverse(localRoot.rightChild);
    private int increment(int i)
    return i++;
    thanks again!

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

  • 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

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

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

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

  • Deep cloning a Binary Tree

    Hi, I have a class called DigitalTree that acts like a binary tree, storing nodes that each have a "key" which is a long value, and then puts each node into the tree in its correct place, binary tree style. I am trying to deep clone the tree, but for some reason my recursive cloning method isn't working. If anyone can see a problem in my code or has any tips for me, it would be greatly appreciated. Thanks.
    public Object clone()
           DigitalTree<E> treeClone = null;
           try
               treeClone = (DigitalTree<E>)super.clone();
           catch(CloneNotSupportedException e)
               throw new Error(e.toString());
           cloneNodes(treeClone, this.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 = (Node<E>)currentNode.clone();
               cloneNodes(treeClone, currentNode.left, cloneNode.left);
               cloneNodes(treeClone, currentNode.right, cloneNode.right);
       }In the Node class:
    public Object clone()
              Node<E> nodeClone = null;
              try
                   nodeClone = (Node<E>)super.clone();
              catch(CloneNotSupportedException e)
                   throw new Error(e.toString());
              return nodeClone;
           }

    Hello jssutton
    Your question inspired me to try my own binary tree and cloning. My cloning algorithm is similar to yours but with one difference.
    In my class Tree defined as:
    class Tree<T extends Comparable>
    I have:
        private void deepCopyLeft(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mLeft = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mLeft);
            deepCopyRight(src.mRight, dest.mLeft);
        private void deepCopyRight(TreeNode<T> src, TreeNode<T> dest) {
            if (src == null) return;
            dest.mRight = new TreeNode<T>(src.mValue);
            deepCopyLeft(src.mLeft, dest.mRight);
            deepCopyRight(src.mRight, dest.mRight);
        public Tree<T> deepCopy() {
            if (root == null) return new Tree<T>();
            TreeNode<T> newRoot = new TreeNode<T>(root.mValue);
            deepCopyLeft(root.mLeft, newRoot);
            deepCopyRight(root.mRight, newRoot);
            return new Tree<T>(newRoot);
        }Its a similar recursive idea, but with 2 extra functions. I hope that helps. I don't have time right now to pinpoint the problem in your routine. Good luck.

  • Recover a Binary Tree

    Ok people I need help!
    I want to create, from a pre-order and in-order sequences, the post-order sequence! Obviously there are no repeated elements (characters from A to Z at this case).
    The tree root it's the first character from pre-order and after that it's easy to take left and right sequences.
    I found an interesting explanation: http://www.dcs.kcl.ac.uk/staff/pinz...st/html/l7.html
    I've tried everything to make it recursive I think that's the best way to do it but somehow I can't make it work! My last code:
    import java.io.*;
    import java.util.*;
    public class Problem
            static String readLn (int maxLg)  // utility function to read from stdin
                byte lin[] = new byte [maxLg];
                int lg = 0, car = -1;
                try
                    while (lg < maxLg)
                        car = System.in.read();
                        if ((car < 0) || (car == '\n')) break;
                        lin [lg++] += car;
                catch (IOException e)
                    return (null);
                if ((car < 0) && (lg == 0)) return (null);  // eof
                return (new String (lin, 0, lg));
            public static void main (String []args)
                    for (int set = Integer.parseInt(readLn(10).trim()); set != 0; set--)
                            StringTokenizer tok = new StringTokenizer(readLn(100).trim()," ");
                            String preOrd = tok.nextToken();
                            String inOrd = tok.nextToken();
                            char root = preOrd.charAt(0);
                            BinaryNode tree = new BinaryNode(root);
                            // Left and right from inOrd
                            tok = new StringTokenizer(inOrd,Character.toString(root));
                            String inOrdLeft = tok.nextToken();
                            String inOrdRight = tok.nextToken();
                            // Take left and right from preOrd
                            String preOrdLeft = preOrd.substring(1,inOrdLeft.length()+1);
                            String preOrdRight = preOrd.substring(inOrdLeft.length()+1);
                            tree.left = work (preOrdLeft, 0, inOrdLeft);
                            tree.right = work (preOrdRight, 0, inOrdRight);
                            tree.printPostOrder();
                            System.out.println();
            public static BinaryNode work (String preOrd, int preOrdPoint, String inOrd)
                    char    nodeChr = preOrd.charAt(preOrdPoint);
                    String  nodeStr = Character.toString(nodeChr);
                    //System.out.println("Root: "+nodeStr+" preOrd: "+preOrd+" inOrd: "+inOrd);
                    BinaryNode tempTree = new BinaryNode(nodeChr);
                    StringTokenizer tok = new StringTokenizer(inOrd,nodeStr);  
                    try
                            String newInOrdLeft = tok.nextToken();
                            if (newInOrdLeft.length() == 1) { tempTree.left = new BinaryNode(newInOrdLeft.toCharArray()[0]); }
                            else if (newInOrdLeft.length() != 0) { tempTree.left = work(preOrd, preOrdPoint+1, newInOrdLeft); }
                    catch (NoSuchElementException e) {}
                    try
                            String newInOrdRight = tok.nextToken();
                            if (newInOrdRight.length() == 1) { tempTree.right = new BinaryNode(newInOrdRight.toCharArray()[0]); }
                            else if (newInOrdRight.length() != 0) { tempTree.right = work(preOrd, preOrdPoint+1, newInOrdRight); }
                    catch (NoSuchElementException e) {}
                    return tempTree;
    class BinaryNode
            char chr;
            BinaryNode left = null;
            BinaryNode right = null;
            BinaryNode()
            BinaryNode(char c)
                    this(c, null, null);
            BinaryNode(char c, BinaryNode lt, BinaryNode rt)
                    chr = c;
                    left = lt;
                    right = rt;
            static int size(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return size(t.left) + 1 + size(t.right); }
            static int height(BinaryNode t)
                    if (t == null) { return 0; }
                    else { return 1 + Math.max(BinaryNode.height(t.left), BinaryNode.height(t.right)); }
            void printPostOrder () {
                    if( left != null )
                            left.printPostOrder( ); // Left
                    if( right != null )
                            right.printPostOrder( ); // Right
                    System.out.print(chr); // Node
            static BinaryNode insert (char c, BinaryNode t)
                    Character tmp = new Character(c);
                    if (t == null)
                            t = new BinaryNode(c, null, null);
                    else if (tmp.compareTo(new Character(t.chr)) < 0)
                            t.left = insert(c, t.left );
                    else if (tmp.compareTo(new Character(t.chr)) > 0)
                            t.right = insert(c, t.right);
                    return t;
    }

    I don't know if this is a translation of your C code, but it can reconstruct any binary tree (with letters as nodes and no duplicates) from preorder and inorder traversals. Hope it helps.
    import java.util.*;
    public class ReconstructTree {
        public ReconstructTree() {
        public static void main(String[] args)
            String preorder = "ABDGKLRVWSXCEHMNFIOTUJPYQZ";
            String inorder = "KGVRWLSXDBAMHNECTOUIFPYJZQ";
            Map table = new HashMap();
            Map table2 = new HashMap();
            for(int i=0; i<inorder.length(); i++)
                table.put("" + inorder.charAt(i), new Integer(i));
                table2.put(new Integer(i), "" + inorder.charAt(i));
            List temppreorder = new ArrayList();
            for(int i=0; i<preorder.length(); i++)
                temppreorder.add(table.get("" + preorder.charAt(i)));
            Node root = constructTree(temppreorder);
            printPostOrder(root, table2);
        public static void printPostOrder(Node root, Map table)
            if(root == null)
                return;
            Node left = root.getLeft();
            Node right = root.getRight();
            printPostOrder(left, table);
            printPostOrder(right, table);
            System.out.print(table.get(new Integer(Integer.parseInt("" + root.getValue()))));
        public static Node constructTree(List preorder)
            Iterator it = preorder.iterator();
            int r = ((Integer)it.next()).intValue();
            Node root = new Node(r);
            Node node = root;
            while(it.hasNext())
                node = root;
                int a = ((Integer)it.next()).intValue();
                while(true)
                    r = node.getValue();
                    if(a < r)
                        if(node.getLeft() == null)
                            node.setLeft(new Node(a));
                            break;
                        else
                            node = node.getLeft();
                    else
                        if(node.getRight() == null)
                            node.setRight(new Node(a));
                            break;
                        else
                            node = node.getRight();
            return root;
        public static class Node
            private Node left = null;
            private Node right = null;
            private int value;
            public Node(int v)
                value = v;
            public int getValue()
                return value;
            public Node getLeft()
                return left;
            public Node getRight()
                return right;
            public void setLeft(Node l)
                left = l;
            public void setRight(Node r)
                right = r;
    }

  • MorseCode Binary Tree

    So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
    For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
    I am sorry for such sloppy code.. I have been changing and rearranging too much.
    import java.io.*;
    import java.util.*;
    public class MorseCode extends BinaryTree{
         static BufferedReader in;
         static BinaryTree<String> bT = new BinaryTree<String>();
    /*     public static void loadTree() throws FileNotFoundException, IOException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
         public static String decode(Character c) throws IOException{
              if(c.equals("null")){
                   return "";
              }else if(c.equals(" ")){
                   return " ";
              }else{
                   return (":" + find(c));
         public static String find(Character c) throws IOException, FileNotFoundException{
              in = new BufferedReader(new FileReader("MorseCode.txt"));
              bT = readBinaryTree(in);
              Queue<BinaryTree> data = new LinkedList<BinaryTree>();
              BinaryTree<String> tempTree = bT;
              String temp = null;
              Character tempChar = null;
              data.offer(tempTree);
              while(!data.isEmpty()){
                   tempTree = data.poll();
                   temp = tempTree.getData();
                   tempChar = temp.charAt(0);
                   if(tempChar.equals(c)){
                        break;
                   data.offer(tempTree.getRightSubtree());
                   data.offer(tempTree.getLeftSubtree());
              return temp.substring(2);               
         public static void main(String[] args) throws FileNotFoundException, IOException{
              Scanner scan = new Scanner(new FileReader("encode.in.txt"));
              String s = "";
              String temp = "";
              while(scan.hasNextLine()){
                    temp = scan.nextLine();
                    for(int i = 0; i < temp.length(); i++){
                         s = s + decode(temp.charAt(i));
              System.out.println(s);
    /** Class for a binary tree that stores type E objects.
    *   @author Koffman and Wolfgang
    class BinaryTree <E> implements Serializable
      //===================================================
      /** Class to encapsulate a tree node. */
      protected static class Node <E> implements Serializable
        // Data Fields
        /** The information stored in this node. */
        protected E data;
        /** Reference to the left child. */
        protected Node <E> left;
        /** Reference to the right child. */
        protected Node <E> right;
        // Constructors
        /** Construct a node with given data and no children.
            @param data The data to store in this node
        public Node(E data) {
          this.data = data;
          left = null;
          right = null;
        // Methods
        /** Return a string representation of the node.
            @return A string representation of the data fields
        public String toString() {
          return data.toString();
      }//end inner class Node
      //===================================================
      // Data Field
      /** The root of the binary tree */
      protected Node <E> root;
      public BinaryTree()
        root = null;
      protected BinaryTree(Node <E> root)
        this.root = root;
      /** Constructs a new binary tree with data in its root,leftTree
          as its left subtree and rightTree as its right subtree.
      public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
        root = new Node <E> (data);
        if (leftTree != null) {
          root.left = leftTree.root;
        else {
          root.left = null;
        if (rightTree != null) {
          root.right = rightTree.root;
        else {
          root.right = null;
      /** Return the left subtree.
          @return The left subtree or null if either the root or
          the left subtree is null
      public BinaryTree <E> getLeftSubtree() {
        if (root != null && root.left != null) {
          return new BinaryTree <E> (root.left);
        else {
          return null;
      /** Return the right sub-tree
            @return the right sub-tree or
            null if either the root or the
            right subtree is null.
        public BinaryTree<E> getRightSubtree() {
            if (root != null && root.right != null) {
                return new BinaryTree<E>(root.right);
            } else {
                return null;
         public String getData(){
              if(root.data == null){
                   return "null";
              }else{
                   return (String) root.data;
      /** Determine whether this tree is a leaf.
          @return true if the root has no children
      public boolean isLeaf() {
        return (root.left == null && root.right == null);
      public String toString() {
        StringBuilder sb = new StringBuilder();
        preOrderTraverse(root, 1, sb);
        return sb.toString();
      /** Perform a preorder traversal.
          @param node The local root
          @param depth The depth
          @param sb The string buffer to save the output
      private void preOrderTraverse(Node <E> node, int depth,
                                    StringBuilder sb) {
        for (int i = 1; i < depth; i++) {
          sb.append("  ");
        if (node == null) {
          sb.append("null\n");
        else {
          sb.append(node.toString());
          sb.append("\n");
          preOrderTraverse(node.left, depth + 1, sb);
          preOrderTraverse(node.right, depth + 1, sb);
      /** Method to read a binary tree.
          pre: The input consists of a preorder traversal
               of the binary tree. The line "null" indicates a null tree.
          @param bR The input file
          @return The binary tree
          @throws IOException If there is an input error
      public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
        // Read a line and trim leading and trailing spaces.
        String data = bR.readLine().trim();
        if (data.equals("null")) {
          return null;
        else {
          BinaryTree < String > leftTree = readBinaryTree(bR);
          BinaryTree < String > rightTree = readBinaryTree(bR);
          return new BinaryTree < String > (data, leftTree, rightTree);
      }//readBinaryTree()
      /*Method to determine the height of a binary tree
        pre: The line "null" indicates a null tree.
          @param T The binary tree
          @return The height as integer
      public static int height(BinaryTree T){
            if(T == null){
               return 0;
          }else{
               return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
      public static String preOrderTraversal(BinaryTree<String> T){
          String s = T.toString();
          String s2 = "";
          String temp = "";
          Scanner scan = new Scanner(s);
          while(scan.hasNextLine()){
               temp = scan.nextLine().trim();
               if(temp.equals("null")){
                   s2 = s2;
              }else{
                   s2 = s2 + " " + temp;
          return s2;
    }//class BinaryTree

    As well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
    public static void main(String[] args) throws FileNotFoundException, IOException{
        //Scanner scan = new Scanner(new FileReader("encode.in.txt"));
        Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
    public static String decode(Character c) throws IOException{
        if(c.equals("null")){
    c is a Character so it will never be the case that it is equal to the string n-u-l-l.
    Perhaps the behaviour of each of these methods needs to be (documented and) tested.

  • 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

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

Maybe you are looking for

  • Problem in new 1% higher education cess as per budget 07

    Hi, we have done the configuration for the new 1% higher education cess in SAP.we have uploaded the relevant patches, done the required manuel changes, also completed the changes in MM and SD module.All the changes were done as per SAP notes.But stil

  • Cannot find the root of your orgchart. The orgchart box may have been delet

    Hi All I have searched to forum for similar issues, but none seem to apply to the errors I get in the CDS log. When try-ing to view the Orgchart, in the Orgchart Console I get the following message "Cannot find the root of your orgchart. The orgchart

  • ITunes keeps wiping my library.

    This is the 4th time this has happened. I have several playlists and albums, along with many songs from CDs and some LEGALLY downloaded for free from Nico Nico Douga (it has a sister site that allows you to download their videos as MP3s.) What happen

  • Tax Segments in IDOC Processing

    Hello, For intercompany postings of the Sales and corresponding Purchsing invoices we have set up the IDOC process. In this porcess, once we post the Billing Document then an IDOC posts the corresponding Purchasing Invoice with MIRO. We have also set

  • Change new message highlight color

    When you first use Mail the selected message is highlighted with a blue color to show what message you are viewing in the Inbox pane. Somehow, I changed this highlight color to a green but now cannot figure out were to find that command. Help!