Breadth First Traversal of a Network

I am working on a task that reads from file a list of towns and displays their adjacent towns and distances.
I then have to do a breath first traversal of the network and am encountering problems in my code. Could someone please have a look at my code and see if they can see where I am going wrong.
Thank you
import java.awt.event.*;
import java.awt.*;
import java.util.Stack;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
public class BreadthFirstTraversal extends JFrame implements ActionListener
     private Container c;
     private JPanel pNorth,pCentre,pSouth;
     private JButton btnExit;
     private JScrollPane jsp;
     private JLabel lblDummy;
     private JTextArea display;
     private Border border;
     BreadthFirstTraversal(Vertex vStart)
          c = getContentPane();
          pNorth = new JPanel();
          lblDummy = new JLabel();
          pNorth.add(lblDummy);
          pCentre = new JPanel();
          display = new JTextArea(20,50);
          display.setFont(new Font("Serif",Font.PLAIN,18));
          jsp = new JScrollPane(display);
          border = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
          jsp.setBorder(border);
          pCentre.add(jsp,BorderLayout.CENTER);
          pSouth = new JPanel();
          btnExit = new JButton("Exit");
          btnExit.addActionListener(this);
          pSouth.add(btnExit);
          breadthFirst(vStart);
          c.add(pNorth,BorderLayout.NORTH);
          c.add(pCentre,BorderLayout.CENTER);
          c.add(pSouth,BorderLayout.SOUTH);
     private void breadthFirst(Vertex start)
          lblDummy.setText("Breadth-First Traversal");
          Arc currentArc = new Arc();
          String currentTown;
          List listStart,listRear,listNext;
          listStart=null;listRear=null;listNext=null;
          listStart=new List(start.getTown());//create first entry to queue
          listRear=listStart;//set the rear to point to start of Queue as well
          start.setProcessed(true);//set the town to processed
          while(listStart!=null)//while queue is not empty
               currentTown=listStart.getTown();//set current town to look at first
               display.append(" "+listStart.getTown()+"; ");//append town to display text area
               listStart=listStart.getLink();//leave the queue
               currentArc=getAdjacentLink(start,currentTown);//get the link to the adjacent towns that need checked
               //put adjacent towns on stack if not been processed
               while(currentArc!=null)
                    if(!townIsProcessed(start,currentArc.getTwn()))//it its not processed
                         if(listStart==null)//if queue is empty
                              listStart=new List(currentArc.getTwn());//create the start of the queue
                              listRear=listStart;//set the rear to point at start
                         else
                              //Add to Rear of Queue
                              listNext=new List(currentArc.getTwn());//create next element to add to queue
                              listRear.setLink(listNext);//set the rear to point at the new item
                              listRear=listNext;//set the rear to the new item that was added
                         setProcessed(start, currentArc.getTwn());//set that town to have been processed
                    currentArc=currentArc.getLink();//move to next Arc
          clearStatus(start);//set all prosessed booleans back to false
     public Arc getAdjacentLink(Vertex start, String town)
          Arc link= new Arc();
          while(start!=null)
               if(start.getTown().compareTo(town)==0)
                    link=start.getAdjacentTowns();
               start=start.getLink();//move to next vertex
          return link;
     public void clearStatus(Vertex start)
          while(start!=null)
               start.setProcessed(false);
               start=start.getLink();
     public void setProcessed(Vertex start, String twn)
          while(start!=null)
               if(start.getTown().compareTo(twn)==0)
                    start.setProcessed(true);
               start=start.getLink();
     public boolean townIsProcessed(Vertex start,String town)
          while(start!=null)
               if(start.getTown().compareTo(town)==0)
                    if(start.isProcessed())
                         return true;
                    else
                         return false;
               start=start.getLink();
          return false;
     public void actionPerformed(ActionEvent e)
}There are no errors in the code itself but when I try to run it I am getting the following messages in the console:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
     at java.lang.String.compareTo(Unknown Source)
     at BreadthFirstTraversal.townIsProcessed(BreadthFirstTraversal.java:130)
     at BreadthFirstTraversal.breadthFirst(BreadthFirstTraversal.java:68)
     at BreadthFirstTraversal.<init>(BreadthFirstTraversal.java:39)
     at NetworkMenu.actionPerformed(NetworkMenu.java:161)
     at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
     at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
     at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
     at javax.swing.AbstractButton.doClick(Unknown Source)
     at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
     at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
     at java.awt.Component.processMouseEvent(Unknown Source)
     at javax.swing.JComponent.processMouseEvent(Unknown Source)
     at java.awt.Component.processEvent(Unknown Source)
     at java.awt.Container.processEvent(Unknown Source)
     at java.awt.Component.dispatchEventImpl(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
     at java.awt.Container.dispatchEventImpl(Unknown Source)
     at java.awt.Window.dispatchEventImpl(Unknown Source)
     at java.awt.Component.dispatchEvent(Unknown Source)
     at java.awt.EventQueue.dispatchEvent(Unknown Source)
     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
     at java.awt.EventDispatchThread.run(Unknown Source)

It's not necessarily town that's causing the
NullPointerException. If start is null, then calling
getTown() on it would throw a NullPointerException.
If whatever getTown() returned was null, then calling
compareTo() on it would throw a NullPointerException.
So there are three places on that line where it could
be thrown.Wrong and, uh, wrong. The stack trace show that
if(start.getTown().compareTo(town)==0)causes a NPE in compareTo's code. If start were null, the NPE would
occur before compareTo could be entered. If getTown() returns
null then again the error occurs before entering compareTo's code.
Therefore, start != null and start.getTown() != null and town == null.

Similar Messages

  • Breadth First Traversal of a Tree...

    Hi,
    I want to make a program to print every node of a tree in a Breadth First Search (BFS)/Traversal. Since, BFS searches a tree in levels (i.e. 1st the root, then it's Children, then Grand Children etc from left to right), this is where I'm stuck. Here is my TreeNode class:
    class TreeNode {
      Object element;
      TreeNode left;
      TreeNode right;
      public TreeNode(Object o) {
        element = o;
    }Each node has a reference to its Children nodes etc. Here is how my tree looks like. Mine is similar to this: http://www.codeproject.com/KB/vb/SimpleBTree.aspx
    All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated.
    Here is my Binary Tree class:
    public class BinaryTree {
         private TreeNode root;
         private int size = 0;
         /** Create a default binary tree */
         public BinaryTree() {
         /** Create a binary tree from an array of objects */
        public BinaryTree(Object[] objects) {
          for (int i = 0; i < objects.length; i++)
            insert(objects);
    /** Insert element o into the binary tree
    * Return true if the element is inserted successfully */
    public boolean insert(Object o) {
    if (root == null)
    root = new TreeNode(o); // Create a new root
    else {
    // Locate the parent node
    TreeNode parent = null;
    TreeNode current = root;
    while (current != null)
    if (((Comparable)o).compareTo(current.element) < 0) {
    parent = current;
    current = current.left;
    else if (((Comparable)o).compareTo(current.element) > 0) {
    parent = current;
    current = current.right;
    else
    return false; // Duplicate node not inserted
    // Create the new node and attach it to the parent node
    if (((Comparable)o).compareTo(parent.element) < 0)
    parent.left = new TreeNode(o);
    else
    parent.right = new TreeNode(o);
    size++;
    return true; // Element inserted
    /** Inorder traversal */
    public void inorder() {
    inorder(root);
    /** Inorder traversal from a subtree */
    private void inorder(TreeNode root) {
    if (root == null) return;
    inorder(root.left);
    System.out.print(root.element + " ");
    inorder(root.right);
    /** Postorder traversal */
    public void postorder() {
    postorder(root);
    /** Postorder traversal from a subtree */
    private void postorder(TreeNode root) {
    if (root == null) return;
    postorder(root.left);
    postorder(root.right);
    System.out.print(root.element + " ");
    /** Preorder traversal */
    public void preorder() {
    preorder(root);
    /** Preorder traversal from a subtree */
    private void preorder(TreeNode root) {
    if (root == null) return;
    System.out.print(root.element + " ");
    preorder(root.left);
    preorder(root.right);
    /** Inner class tree node */
    private static class TreeNode {
    Object element;
    TreeNode left;
    TreeNode right;
    public TreeNode(Object o) {
    element = o;
    /** Get the number of nodes in the tree */
    public int getSize() {
    return size;
    /** Search element o in this binary tree */
    public boolean search(Object o){
    TreeNode temp = root;
    boolean found = false;
    if(temp == null)
    found = false;
    else if(((Comparable)(temp.element)).compareTo(o) == 0 && temp != null)
    found = true;
    else if(((Comparable)temp.element).compareTo(o) > 0){
    root = temp.left;
    found = search(o);
    else{
    root = temp.right;
    found = search(o);
    return found;
    /** Display the nodes in breadth-first traversal */
    public void breadthFirstTraversal(){
    TreeNode temp = root;
    // TreeNode leftChild = temp.left;
    // TreeNode rightChild = temp.right;
    MyQueue s = new MyQueue();
    s.enqueue(root);
    // while (s.getSize() == 0){
    System.out.println(s);
    // private void breadthFirstTraversal(TreeNode node){

    ChangBroot wrote:
    All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated. One simple strategy is to make an ordinary recursive traversal of the tree. Along in the traversal you keep an array of linked lists. When you visit a node you just add it to the list at the entry in the array corresponding to the depth of this node.
    After the traversal you have an array with linked lists. Each list holds the nodes found at a certain tree depth. So each list holds all nodes corresponding to a specific tree "breadth", namely all nodes found at the same tree depth.

  • Breadth-first traversal on a graph.. need help

    I need to make a graph, then run a breadth-first traversal on it. Do I simply make an undirected graph first, then implement the traversal?
    the graph should be like this:
    A - D - G
    B - E - H
    C - F - I
    Message was edited by:
    LuckY07
    Message was edited by:
    LuckY07
    null

    I just would like to print something to the screen showing it ran, such as the letters. What would be an easy way to do this using the DirectedGraph implementation? tks.
    here is my code:
    import ADTPackage.*;     //packages needed to make graph.
    import GraphPackage.*;
    public class graphTraversal
         public static void main(String[] args)
              GraphInterface<String> graph = new DirectedGraph<String>();     //creates graph.
              //adds vertices.
              graph.addVertex("A");
              graph.addVertex("B");
              graph.addVertex("C");
              graph.addVertex("D");
              graph.addVertex("E");
              graph.addVertex("F");
              graph.addVertex("G");
              graph.addVertex("H");
              graph.addVertex("I");
              //adds edges.
              graph.addEdge("A", "B");
              graph.addEdge("A", "D");
              graph.addEdge("A", "E");
              graph.addEdge("D", "G");
              graph.addEdge("D", "G");
              graph.addEdge("G", "H");
              graph.addEdge("H", "I");
              graph.addEdge("I", "F");
              graph.addEdge("F", "C");
              graph.addEdge("C", "B");
              graph.addEdge("B", "E");
              graph.addEdge("E", "H");
              graph.addEdge("E", "F");
              graph.addEdge("F", "H");
              System.out.println("total number of vertices: " + graph.getNumberOfVertices());
              System.out.println("total number of edges: " + graph.getNumberOfEdges());
              graph.getBreadthFirstTraversal("A");
         }     //end main.
    }

  • Breadth first traversal

    Hi,
    I am trying to do a breadth first traversal of a tree, so that the character traversed would be inputted in the correct position in an array. any idea how can i go about it?
    This is my code for the tree:
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    public class Huffman
        static char letters;
        static int frequency;
        static char frequency1;
        static int alphabet;
        static char frqtable [][];
        static char treetable[][];
        static TreeNode myTree[];
        static int i = 0;
        static int j = 0;
        static Scanner in = new Scanner(System.in);
        public static void main (String args[])throws IOException{
            setFrequencyTable();
            treetable = frqtable;
            sortArray(treetable);
            buildHuffmanTree(treetable, alphabet);
           // printGeneralTree();
         public static void setFrequencyTable() throws IOException{
            System.out.println ("Please enter number of distinct alphabet");
            alphabet = in.nextInt();
            frqtable = new char[alphabet][2];
           for (int count = 0; count<alphabet; count++){
                System.out.println ("Enter the character");
                letters = (char) System.in.read();
                frqtable[i][j] = letters;
                System.out.println ("Enter frequency");
                frequency = in.nextInt();
                frequency1 = Integer.toString(frequency).charAt(0); ;
                frqtable[i][j+1] = frequency1;
                i = i+1;
                j = 0;
        public static void sortArray (char[][]treetable){
            char templetter;
            char tempfrq;
          for (int j=0; j < frqtable.length; j++) {
            for (int i=0; i < frqtable.length-1; i++) {
                  if((treetable[1]) < (treetable[i+1][1])){
    tempfrq = (treetable[i][1]);
    templetter = (treetable[i][0]);
    (treetable[i][1]) = (treetable[i+1][1]);
    (treetable[i][0]) = (treetable[i+1][0]);
    (treetable[i+1][1]) = tempfrq;
    (treetable[i+1][0]) =templetter;
    public static void printInOrder(TreeNode root) {
    if (root != null) {
    printInOrder(root.left);
    if(root.ch == '\0'){
    System.out.println(" Traversed " + root.count);
    }else{
    System.out.println(" Traversed " + root.ch);
    printInOrder(root.right);
    public static void buildHuffmanTree(char [][] treetable, int alphabet){
    myTree = new TreeNode [alphabet];
    TreeNode leftNode, rightNode;
    TreeNode newNode = null;
    for ( int i = 0; i < alphabet; i++ ){
    myTree[i] = new TreeNode (treetable[i][0], Character.getNumericValue(treetable[i][1]));
    for (int j =((myTree.length)-1); j>0; j--){
    newNode = new TreeNode(myTree[j], myTree[j-1]);
    myTree[j] = null;
    myTree[j-1] = null;
    // j--;
    if(j!=1){
    for(int c = 0; c<(j-1); c++){
    if(myTree[c].count <= newNode.count){
    for(int x = alphabet-1; x>c; x--){
    myTree[x] = myTree[x-1];
    myTree[c] = newNode;
    c= j-1;
    }else{
    myTree[0] = newNode;

    Doobybug whether or not this is an assignment, home work, basic exercise or weekly puzzle, it has been derived for a reason, to get your mind thinking like a computer scientist. Of course if one had no knowledge of the breadth first traversal then the first intelligent action on their behalf would be to do some research, aka google/wikipedia. Hopefully at which point you understand the algorithm and you can apply a general set of instructions on a piece of paper using a pen. Write down exactly what is required with your understanding of the algorithm, draw a very basic binary tree and apply your technique. Does it work? If not don't worry this was only your first attempt, think about whats missing and apply a new technique based upon the algorithm again using only pen and paper.
    The sooner you can think for yourself the better.
    p.s. That was my technique whilst learning binary trees in first year.
    Mel

  • Breadth first traversal in PLSQL (How to implement Queue?)

    Hi,
    I have a tree Stored in different tables,basically its a XML tree and all the nodes are stored in different tables,those tables are related with integrity constraints.I want to traverse the tree using BFS algo,how can i implement a queue using PL/SQL.if u have any reference doc or any sample code to implement a queue please post in this thread.
    Thanks
    somy

    fgb wrote:
    Instead of enqueuing just rt.right, you need to enqueue all of the node's siblings before enqueuing rt.left. This would be easier if you knew whether a node was the leftmost child and only enqueing its siblings in that case.
    Thanks, that actually did it right there, I should have realized that.
    The modified code is this, for anyone interested:
    if(rt != null)
                queue.enqueue(rt);
                while(!queue.isEmpty())
                    rt = (Node)queue.dequeue();
                    left = rt.left;
                    if(left != null && left.right != null)
                        right = left.right;
                    else
                        right = null;
                    visit(rt);
                    if(left != null)
                        queue.enqueue(left);
                        while(right != null)
                            queue.enqueue(right);
                            if(right.right != null)
                                right = right.right;
                            else
                                right = null;
            }

  • Bfs - A breadth-first version of find

    I'm writing a breadth-first version of find.  It's available on the AUR(4), and the code is on GitHub.
    Currently it doesn't support any of find's options, but I plan to add support for the common ones.  It does support a "-nohidden" flag that filters out dotfiles, something surprisingly difficult to do with find.  It also supports colorization, respecting LS_COLORS.
    The reason I'm writing it is mainly to integrate it with fzf, a terminal fuzzy finder.  fzf uses find by default, which means it will often fully explore a very deep directory tree before reaching the nearby file I'm looking for.  bfs ensures that shallower files always show up before deeper ones, which usually means it finds the file I want sooner.  The colorization is also nice:
    $ bfs -color -nohidden | fzf --ansi
    Last edited by tavianator (2015-06-20 04:42:39)

    ChangBroot wrote:
    All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated. One simple strategy is to make an ordinary recursive traversal of the tree. Along in the traversal you keep an array of linked lists. When you visit a node you just add it to the list at the entry in the array corresponding to the depth of this node.
    After the traversal you have an array with linked lists. Each list holds the nodes found at a certain tree depth. So each list holds all nodes corresponding to a specific tree "breadth", namely all nodes found at the same tree depth.

  • When to go for Breadth first search over depth first search

    hi,
    under which scenarios breadth first search could be used and under which scenarios depth first search could be used?
    what is the difference between these two searches?
    Regards,
    Ajay.

    No real clear-cut rule for when to use one over the other. It depends on the nature of your search and where you would prefer to find results.
    The difference is that in breadth-first you first search all immidiate neighbours before searching their neighbours (sort of like preorder traversal). Whereas in depth-first you search some random (or otherwise selected) neighbour and then a neighbour of that node until you can't go deeper (i.e., you've searched a neighbour that has no other neighbours). This probably isn't a very clear explanation, perhaps you'll find this more helpful: http://www.ics.uci.edu/~eppstein/161/960215.html
    If you would prefer to find results closer to the origin node, breadth first would be better. If you would prefer to find results further away use depth first.

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

  • Breadth First Search (More of a Logic Question)

    Hey guys, I'm having a logic block with a Breadth First Search using a queue.
    Basically the way Breadth First Search works is that it expands all of the nodes one level at a time until it finds the result. I quickly whipped out a flash to demonstrate what I believe is the Breadth First Search.
    http://www.nxsupport.com/dimava/bfs.swf
    I wrote the code to do the algorithm, However if I just output the queue it shows all of the excess "potential" nodes and not just the direct route. For example, with the flash file linked above, it would show ABECGFC, instead of just ABCD.
    I realise that I could trace back from the end to see which of the nodes D is connected to, then which of the nodes C is connected to, etc. But that wouldn't work out if there was more than one path with the same distance leading to the same destination.
    Thanks,
    Dimava

    It's been a long time since college so I may be suggesting a poor way of doing this.
    But suppose you have a queue data type. You can use it in two ways: as a representation of a path from your starting node to your ending node, and as a place to hold paths while you're performing a breadth-first search. (Or you could skip the latter and just use recursion.)
    You wouldn't keep a list of all possible paths. Rather you'd be storing paths that correspond to nodes currently being examined in your breadth-first search.
    So you'd create a queue (representing a path) holding your start node. Then you'd put that queue into the queue that represents your traversal state.
    Then while the traversal queue is not empty, you take out a path (a queue), look at its last element (a node), then create new paths that consist of the current path but each terminating with one of the children of the current node. (Well not really children since it's a graph and not a tree, but you know what I mean.) Repeat until the target node is found.

  • Using depth first traversal to add a new node to a tree with labels

    Hello,
    I'm currently trying to work my way through Java and need some advice on using and traversing trees. I've written a basic JTree program, which allows the user to add and delete nodes. Each new node is labelled in a sequential order and not dependent upon where they are added to the tree.
    Basically, what is the best way to add and delete these new nodes with labels that reflect their position in the tree in a depth-first traversal?
    ie: the new node's label will correctly reflect its position in the tree and the other labels will change to reflect this addition of a new node.
    I've searched Google and can't seem to find any appropriate examples for this case.
    My current code is as follows,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class BasicTreeAddDelete extends JFrame implements ActionListener
        private JTree tree;
        private DefaultTreeModel treeModel;
        private JButton addButton;
        private JButton deleteButton;
        private int newNodeSuffix = 1;
        public BasicTreeAddDelete() 
            setTitle("Basic Tree with Add and Delete Buttons");
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            JScrollPane scrollPane = new JScrollPane(tree);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            JPanel panel = new JPanel();
            addButton = new JButton("Add Node");
            addButton.addActionListener(this);
            panel.add(addButton);
            getContentPane().add(panel, BorderLayout.SOUTH);
            deleteButton = new JButton("Delete Node");
            deleteButton.addActionListener(this);
            panel.add(deleteButton);
            getContentPane().add(panel, BorderLayout.SOUTH);    
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(400, 300);
            setVisible(true);
        public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New Node" + newNodeSuffix++);
                      treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);               
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        public void removeSelectedNode()
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            if (selectedNode != null)
                //get the parent of the selected node
                MutableTreeNode parent = (MutableTreeNode)(selectedNode.getParent());
                // if the parent is not null
                if (parent != null)
                    //remove the node from the parent
                    treeModel.removeNodeFromParent(selectedNode);
        public static void main(String[] arg) 
            BasicTreeAddDelete basicTree = new BasicTreeAddDelete();
    }      Thank you for any help.

    > Has anybody got any advice, help or know of any
    examples for this sort of problem.
    Thank you.
    Check this site: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html

  • Depth/Breadth First Search

    Hello all,
    I am trying to figure out how to do a depth and breadth first search on a graph of Cities, as defined below. I think that I understand the searches, but I am having an extremely difficult time figuring out how to implement them.
    If anyone has any tips, suggestions, or hints (for some reason I think I'm probably just overlooking something simple), I would greatly appreciate them.
    Thanks for any help!
    * to represent an individual city
    public class City {
        String name;
        double latitude;
        double longitude;
        ArrayList<Edge> neighbors;
        //the constructor
        public City(String name, double latitude, double longitude){
            this.name = name;
            this.latitude = latitude;
            this.longitude = longitude;
            this.neighbors = new ArrayList<Edge>();
        //to check if this city is equal to that given city
        public boolean same(City c){
            return this.name.equals(c.name) && this.latitude == c.latitude &&
                this.longitude == c.longitude;
    * to represent an edge between two cities
    public class Edge {
        City city1;
        City city2;
        double dist;
        boolean visited;
        public Edge(City city1, City city2){
            this.city1 = city1;
            this.city2 = city2;
            this.dist = this.distTo();
            this.visited = false;
         * to find the distance between the two cities in an edge
        public double distTo(){
            return Math.sqrt(((this.city1.latitude - this.city2.latitude) *
                    (this.city1.latitude - this.city2.latitude)) +
                    ((this.city1.longitude - this.city2.longitude) *
                    (this.city1.longitude - this.city2.longitude)));
    * to represent a path between two cities as a list
    * of edges
    public class Graph {
        ArrayList<Edge> alist;
        public Graph(ArrayList<Edge> alist){
            this.alist = alist;
    }

    http://en.wikipedia.org/wiki/Breadth-first_search (includes algorithm)

  • Depth first search and breadth first search

    can anyone help for this program. can anyone give me a program for this without using an applet.
    thanks!!!

    can anyone help for this program. can anyone give me a
    program for this without using an applet.
    thanks!!!What are you talking about? What program? Depth-first means you recursively search from root to the first leaf, then go up one level, go down as far as you can, repeat. Breadth-first means you search every node on each level before going on to the next level.

  • Depth First Search, Breadth First Search

    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - Prod
    PL/SQL Release 10.2.0.5.0 - Production
    CORE     10.2.0.5.0     Production
    TNS for Linux: Version 10.2.0.5.0 - Production
    NLSRTL Version 10.2.0.5.0 - Production
    I
    have this table that form a tree where record with column value 'more_left' 0 is located more left than 1 (for example, record with id 2 has a parent id 1 and more left than record with id 7 that also has parent id 1):
    with t as(
      select 2 id,1 parent_id,0 most_left from dual
      union all
      select 7 id,1 parent_id,1 most_left from dual
      union all
      select 8 id,1 parent_id,2 most_left from dual
      union all
      select 3 id,2 parent_id,0 most_left from dual
      union all
      select 6 id,2 parent_id,1 most_left from dual
      union all
      select 9 id,8 parent_id,0 most_left from dual
      union all
      select 12 id,8 parent_id,1 most_left from dual
    union all
      select 4 id,3 parent_id,0 most_left from dual
      union all
      select 5 id,3 parent_id,1 most_left from dual
    union all
      select 10 id,9 parent_id,0  most_left from dual
      union all
      select 11 id,9 parent_id,1 most_left from dual
    select * from t;The problem is to show all the ids, using Breadth First Search and Depth First Search. Tx, in advance.
    Edited by: Red Penyon on Apr 12, 2012 3:39 AM

    Hi,
    I fail to understand how comes there is no row for ID=1 ?
    The topmost parent (the root) should be in the table also.
    For 11g, this would work (as long as the root is in the table) :Scott@my11g SQL>l
      1  WITH t AS
      2       (SELECT 1 ID, 0 parent_id, 0 most_left
      3          FROM DUAL
      4        UNION ALL
      5        SELECT 2 ID, 1 parent_id, 0 most_left
      6          FROM DUAL
      7        UNION ALL
      8        SELECT 7 ID, 1 parent_id, 1 most_left
      9          FROM DUAL
    10        UNION ALL
    11        SELECT 8 ID, 1 parent_id, 2 most_left
    12          FROM DUAL
    13        UNION ALL
    14        SELECT 3 ID, 2 parent_id, 0 most_left
    15          FROM DUAL
    16        UNION ALL
    17        SELECT 6 ID, 2 parent_id, 1 most_left
    18          FROM DUAL
    19        UNION ALL
    20        SELECT 9 ID, 8 parent_id, 0 most_left
    21          FROM DUAL
    22        UNION ALL
    23        SELECT 12 ID, 8 parent_id, 1 most_left
    24          FROM DUAL
    25        UNION ALL
    26        SELECT 4 ID, 3 parent_id, 0 most_left
    27          FROM DUAL
    28        UNION ALL
    29        SELECT 5 ID, 3 parent_id, 1 most_left
    30          FROM DUAL
    31        UNION ALL
    32        SELECT 10 ID, 9 parent_id, 0 most_left
    33          FROM DUAL
    34        UNION ALL
    35        SELECT 11 ID, 9 parent_id, 1 most_left
    36          FROM DUAL
    37  )
    38  select
    39  rt
    40  ,listagg(id,'-') within group (order by lvl,id) BFS
    41  ,listagg(id,'-') within group (order by pth,lvl) DFS
    42  from (
    43  SELECT id, connect_by_root(id) rt, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    44        FROM  t
    45  CONNECT by nocycle  prior ID = parent_id
    46  START WITH parent_id = 0
    47  )
    48* group by rt
    Scott@my11g SQL>/
            RT BFS                            DFS
             1 1-2-7-8-3-6-9-12-4-5-10-11     1-2-3-4-5-6-7-8-9-10-11-12But as long as you're 10g, that is no real help.
    I'll try to think of a way to get that with 10g.
    10g solution for DFS :Scott@my10g SQL>l
      1  WITH t AS
      2  (
      3       SELECT 1 ID, 0 parent_id, 0 most_left FROM DUAL UNION ALL
      4       SELECT 2 ID, 1 parent_id, 0 most_left FROM DUAL UNION ALL
      5       SELECT 7 ID, 1 parent_id, 1 most_left FROM DUAL UNION ALL
      6       SELECT 8 ID, 1 parent_id, 2 most_left FROM DUAL UNION ALL
      7       SELECT 3 ID, 2 parent_id, 0 most_left FROM DUAL UNION ALL
      8       SELECT 6 ID, 2 parent_id, 1 most_left FROM DUAL UNION ALL
      9       SELECT 9 ID, 8 parent_id, 0 most_left FROM DUAL UNION ALL
    10       SELECT 12 ID, 8 parent_id, 1 most_left FROM DUAL UNION ALL
    11       SELECT 4 ID, 3 parent_id, 0 most_left FROM DUAL UNION ALL
    12       SELECT 5 ID, 3 parent_id, 1 most_left FROM DUAL UNION ALL
    13       SELECT 10 ID, 9 parent_id, 0 most_left FROM DUAL UNION ALL
    14       SELECT 11 ID, 9 parent_id, 1 most_left FROM DUAL
    15  )
    16  select max(pth) DFS
    17  from (
    18  select sys_connect_by_path(id,'-') pth
    19  from (
    20  select id,pth,lvl,most_left, row_number() over (order by pth, lvl) rn
    21  from (
    22  select id, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    23  from t
    24  CONNECT by nocycle  prior ID = parent_id
    25  START WITH parent_id = 0
    26  )
    27  order by pth, lvl
    28  )
    29  connect by prior rn= rn-1
    30  start with rn=1
    31* )
    Scott@my10g SQL>/
    DFS
    -1-2-3-4-5-6-7-8-9-10-11-12------
    10g solution for BFS :Scott@my10g SQL>l
      1  WITH t AS
      2  (
      3       SELECT 1 ID, 0 parent_id, 0 most_left FROM DUAL UNION ALL
      4       SELECT 2 ID, 1 parent_id, 0 most_left FROM DUAL UNION ALL
      5       SELECT 7 ID, 1 parent_id, 1 most_left FROM DUAL UNION ALL
      6       SELECT 8 ID, 1 parent_id, 2 most_left FROM DUAL UNION ALL
      7       SELECT 3 ID, 2 parent_id, 0 most_left FROM DUAL UNION ALL
      8       SELECT 6 ID, 2 parent_id, 1 most_left FROM DUAL UNION ALL
      9       SELECT 9 ID, 8 parent_id, 0 most_left FROM DUAL UNION ALL
    10       SELECT 12 ID, 8 parent_id, 1 most_left FROM DUAL UNION ALL
    11       SELECT 4 ID, 3 parent_id, 0 most_left FROM DUAL UNION ALL
    12       SELECT 5 ID, 3 parent_id, 1 most_left FROM DUAL UNION ALL
    13       SELECT 10 ID, 9 parent_id, 0 most_left FROM DUAL UNION ALL
    14       SELECT 11 ID, 9 parent_id, 1 most_left FROM DUAL
    15  )
    16  select max(pth) BFS
    17  from (
    18  select sys_connect_by_path(id,'-') pth
    19  from (
    20  select id,pth,lvl,most_left, row_number() over (order by lvl, pth) rn
    21  from (
    22  select id, sys_connect_by_path(most_left,'-') pth, level lvl, most_left
    23  from t
    24  CONNECT by nocycle  prior ID = parent_id
    25  START WITH parent_id = 0
    26  )
    27  order by lvl, pth
    28  )
    29  connect by prior rn= rn-1
    30  start with rn=1
    31* )
    Scott@my10g SQL>/
    BFS
    -1-2-7-8-3-6-9-12-4-5-10-11There might certainly have better ways...

  • HT4623 I am using iPhone 5 by Cricket and it is international unlock and i tried that when i entered the sim first time it gives network but when i take out the sim and entered the sim again it doesnt give network

      I am using iPhone 5 by Cricket and it is international unlock and i tried that when i entered the sim first time it gives network but when i take out the sim and entered the sim again it doesnt give network and keep searching why ?? Is this problem can be resolve

    Don't know where you got that idea, all US Cricket iPhones are carrier locked, with NO way to get them officially unlocked, as Cricket DOES NOT offer official unlocking for the iPhone.

  • First home sharing, now network problems

    I can't seem to get Apple TV to work for me. I've followed the setup instructions and troubleshooting guide, but so far it has been a nightmare. I am connected via wireless router. When I first setup the Atv, the network worked fine, but I couldn't get home sharing to work. Home sharing was turned on both on my computer and on the Atv, but it did not appear in my devices in Itunes and would not register on the Atv. I checked my firewall and even temporarily disabled it to be sure, but no luck. After several reboots and a complete reinstall of Itunes 10.1, now the Atv will not even attempt to connect to the network. Even if I try to manually configure the ipaddress, it does not take on the apple TV. Tomorrow I will get another ethernet cable and try the wired approach, but seriously this thing should not be that hard to setup. I've tried everything in the user guide/troubleshooting tips and a few things that seemed to work for others in this forum (mostly pulling cables and restarting hardware/software), but I am out of ideas. Any suggestions??

    Finally solved this issue for me! Turns out it was my Intego VirusBarrier X6. After my initial use of ATV2 and accessing the iTunes library on my iMac, VirusBarrier began blocking the IP address of the ATV on my iMac to prevent a perceived data flood. All I had to do was open the Anti-Vandal tab within VirusBarrier and identify the ATV's IP address as trusted. (The ATV IP address is found under Settings-->General-->Network.)
    Thanks to an earlier post by CaptPulver.

Maybe you are looking for