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.

Similar Messages

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

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

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

  • Is SQR #include a depth first search or breadth first search alrgorithm

    Just wondering if SQR compiler is a dfs or bfs algorithm? I am guessing a dfs since includes can show up at the beginning or end of the sqr or sqc definition but position is relevant. So a few questions that branch off of that one.
    I have successfully included file filea.sqc and fileb.sqc in myfile.sqr, then included file subfile.sqc in both filea.sqc and fileb.sqc. There seemed to be no error message, so I am wondering how the file include works. I would think from a compiler point of view, if we included the same procedure or function twice, we should do one of three things - ignore the second instance (do nothing), override the first instance, or throw an error.
    So, anyone know how the compiler stack is built?

    The documentation doesn't help much, but if you want to prevent an include from being loaded more than once, you should be able to use a combination of compiler directives, i.e. #IFNDEF and #DEFINE.
    In your example, if you code subfile.sqc like
    #IFNDEF SUBFILE_INCLUDED
    #DEFINE SUBFILE_INCLUDED Y
    begin-procedure subfile_proc
    #ENDIFthen you should only get one copy of the code between the #IFNDEF-#ENDIF statements.
    You could probably use something similar to test how SQR handles multiple includes of the same file. Try something like
    #IFDEF SUBFILE_INCLUDED
    Display 'Subfile included twice'
    #ENDIF
    #IFNDEF SUBFILE_INCLUDED
    #DEFINE SUBFILE_INCLUDED Y
    #ENDIFand see if the message is displayed.
    Regards,
    Bob

  • Need help finalizing breadth-first search function...

    I have a map with bidirectional links and I am to find the shortest path so the first path found will be good for me. I tried follow the algorithm for BFS and it shows below. However, I am not sure when/where/what I should return per loop. I would like to get a list of Nodes (map represented by numeric node numbers). I dont think returning a list is right for this recursion so i put down int for now... I think the steps are right but just not sure how to get the result.... Please help! thanks!
    public int(?) getShortestPath() {
              int currentNode = bfsQueue.remove();//already has Root from start
              if (currentNode == destNode) {
                   shortestPathFound = true;
              } else {
                   ArrayList<Integer> temp = getChildrenLinks(currentNode);
                   for (int x=0; x< temp.size(); x++) {
                        bfsQueue.add(temp.get(x));
              if (bfsQueue.size() == 0) {
                   return null;
              } else if (shortestPathFound == false){
                   getShortestPath();
              return null;
         }

    You have almost all variable defined outside your method. You "should" declare them inside. Also, there is no need to make a recursive call (which makes it easier to return your path).
    Here's a debugged version of a BFS:
    Say you have the following edges:
    1 <--> 2
    1 <--> 3
    2 <--> 5
    2 <--> 6
    3 <--> 4
    4 <--> 5
    5 <--> 6
    5 <--> 7
    7 <--> 8
    7 <--> 9
    8 <--> 9
    8 <--> 10A picture of this would look like:
    1 --- 2 --- 6
    |      \___ |     9
    |          \|    /|
    3 --- 4 --- 5   / |
                |  /  |
                | /   |
                7 --- 8 --- 10And you want to find the shortest path from 1 to 8.
    Create a stack that holds all "layers" (a list of numbers) that you are discovering. So you start with an empty STACK and push the start node (in a list) on it:
    STACK {
      {1} // layer 1
    }Pop the last "layer" from your STACK and collect all it's unvisited neighbours. All these unvisited neighbours are the next layer which should be pushed on your STACK. Now your STACK looks like:
    STACK {
      {1}   // layer 1
      {2,3} // layer 2
    }Again pop the last layer from your stack (this is now {2,3}) and collect all it's unvisited neighbours and push these on your STACK. Now your STACK looks like:
    STACK {
      {1}     // layer 1
      {2,3}   // layer 2
      {4,5,6} // layer 3
    }Keep pushing new "layers" on your STACK until you stumble upon your destination node (8 in this example). So, when you get to your destination node, your STACK looks like:
    STACK {
      {1}     // layer 1
      {2,3}   // layer 2
      {4,5,6} // layer 3
      {7}     // layer 4
      {8,9}   // layer 5
    }Now that you have gotten to your destination, it's time to find the actual path by back-tracking through your "layers" where you must "jump" from "layer" N to a "layer" N-1 (you can only "jump" to a lower "layer"):
    The back-tracking will look like:
    STACK {
      {1}     // layer 1
       | 
      {2,3}   // layer 2
      {4,5,6} // layer 3
      {7}     // layer 4
       |
      {8,9}   // layer 5
    - 8 (in layer 5) is connected to 7 (in layer 4)
    - 7 (in layer 4) is connected to 5 (in layer 3)
    - 5 (in layer 3) is connected to 2 (in layer 2)
    - 2 (in layer 2) is connected to 1 (in layer 1)So, your shortest path is: [1,2,5,7,8]
    HTH

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

  • When we type a search item in firefox on my laptop then it shows the result then on second or third or more new search that is typing a new search it sticks to the first searched item

    when we type a search item in firefox on my laptop then it shows the result then on second or third or more new search that is typing a new search it sticks to the first searched one

    Tried that. Also tried SUPERAntiSpyware, ccleaner, HitmanPro. Removed anything that was reported. Problem persists.
    Chrome is also affected. But couldn't find any alternative way of not having Ask.com loaded as did in Firefox.
    Internet Explorer was initially affected. After the Ask.com search engine is removed that problem appears to have gone away.
    12/9/2014
    Interestingly, yesterday afternoon the Chrome browner new tab no longer hijacked by Ask.com. The symptom was there in the morning and had gone away in the late afternoon. Nothing was done except a few days ago I blocked everything on that page. The problem with Firefox continue to persist I didn't do the same blocking on it. I am going to try the same and then use anti-spyware to clear away all cookies and see what happens.

  • Depth First Search w/o Recursion

    I am trying to use Depth First Search for 2-D maze, and I was just wondering if there was a straight forward and easy way of doing DFS of a maze without using recursion. Or is recursion the really only way you do DFS without invoking a lot of messy variables to hold temporary information.

    itereation instead of recursion...can you be a little more discriptive.
    For recursion I can understand how it works because when you pop out of one recursive cycle you got to the next command. So basically
    move{
    if you can
    go left
    move()
    go right
    move()
    go up
    move()
    go down
    move()
    else
    pop out of recursion
    hopefully this pseudocode makes some sense. But absically lets say with my maze I go right 3 times then can't go right anymore...well when that happens it will try to go right, because after calling move() under "go left" the next step would just be to go left. But I don't see how this can be done iteratively. If somebody can explain it pseudocode that would be cool too.

  • Any way to have file size included in the first search in finder?

    Is it possible to somehow show file sizes when doing a search in finder?
    On Panther, it was very helpful to have the file sizes listed. This immediately revealed whether the photoshop files I was looking for were full size or reduced.
    But when I run a search in Snow Leopard it only shows name, kind and last opened. Otherwise I have to also add a second search to add in file size.
    Any way to have file size included in the first search?
    Thanks!

    Well, I wish I could take credit for knowing it was there before two days ago... but I dropped my laptop a couple months ago and it finally died for good on Friday, and I noticed this on the new laptop when setting up my Finder preferences.

  • Search more than one location at a time?

    Hello,
    I spend a lot of my time searching for files in our studio (I maintain the archives, backups, file systems, etc.) and I have to search across a number of locations (a number of local drives, specific locations/folders on various servers, etc.). Right now all our machines in the studio are on Tiger and I'm considering upgrading to 10.5, but the one major roadblock I've come across thus far is the ability to search various locations in 10.5. In 10.4 I was able to select multiple locations (local machine, specific folders on file and archive servers, etc.) all at once to find what I need. In 10.5 I've been unable to find a way to search more than one location at a time. Am I missing something, or has Apple removed the ability to search like this? This would be a serious roadblock for me as it would mean each search I do would have to be done 2-5 times, depending on what I'm looking for and where it could be found. I've even tried created a "search" folder which contains alias folders to all the places I'd normally search, but this didn't work.
    If anyone has any advice on how I could possible do this, it would be greatly appreciated!
    Regards,
    Kristin.

    Yea, I understand how to search in 10.5 (either using the magnify glass in top right, or command-F) but what I'm trying to figure out is how to search "This Mac" AND a folder on a server at the same time. In 10.4 you could just click on the places you wanted to search, but in 10.5 this option is gone. When you search "This Mac" (no matter how you customize your search), it only searches the Mac your on and mounted drives via USB and FireWire. It doesn't search other networked computers and servers and you have no option to search a specific folder on a networked computer or server unless you actually navigate to that folder and run the search (at which point you're only searching that folder and no longer also searching the "This Mac").
    You can customize a lot of things, but what feature that's lacking in the 10.5 searching is the ability to search specific/various locations across a network.
    In the studio it would be specific the computer I'm working on (a Mac Pro [not Macbook Pro]) and it's connected to 20 other Macs (G5 towers, Intel iMacs and Mac Pros) and two servers (Xserves). I only need to search specific locations on these systems, which you can't seem to do in 10.5. In fact, I haven't even found a way to search all the computers on the network, let alone specific locations on these computers on the network, all at once.
    I've been trying to figure this out all weekend (at home) via the following setup:
    - Intel iMac
    - External FireWire drive mounted on Intel iMac
    - G4 Server "connected" via Intel iMac
    In each of these locations I've placed the following folders:
    #1 - FIND THIS FILE - IMAC DESKTOP (on iMac desktop)
    #2 - FIND THIS FILE - FW HD (on external FW drive mounted to iMac)
    #3 - FIND THIS FILE - G4 DESKTOP (on G4 Server desktop connected to iMac)
    When I run the search, if I select "This Mac" it finds both folders #1 & #2, but NOT #3.
    The only way I can get the search to find #3 is to navigate via Finder to the G4 and run a search. But, now it's only searching the G4 Server and thus only find #3 and NOT #1 or #2.
    I can either search "This Mac" (and mounted drives) OR the G4 Server, but not both.
    At this point I have tried everything I can to get this to work, but nothing. I believe there is NO WAY to search various locations (especially various specific locations) across the network and that Apple has removed this ability in 10.5. I would LOVE if someone could prove me wrong!?
    Regards,
    Kristin.

  • I have inadvertently infringe copyright on facebook and they have subsequently barred me from uploading any more videos. The question I need answered is ( and not able to find the answer on any of you help pages).....  Do the following have free copyright

    I have inadvertently infringe copyright on facebook and they have subsequently barred me from uploading any more videos.
    The question I need answered is ( and not able to find the answer on any of you help pages).....
    Do the following have free copyright to publish on facebook and U Tube?
    1.Garage band sounds?
    2.Slide show...Sample music and Theme music?
    3.iMovie...iMovie sounds and iLife sounds ie.Medal Ceremony and Memorial etc?
    I note one can publish to shared net places directly from iMovie so one assumes these are copyright free for non-profit making and non-comercial use.
    It is impossible to contact apple direct.No email address.We put our selves at risk without this knowledge and like applemac, facebook will not communicate direct.Will applemac please take responsibility for copyright/the above that they are all too willing to sell to us but not support us with that knowledge.
    I have Mac OS X Snow Leopard version 10.6.2 (2009 bought in 2010)

    Thank you Klaus1.The large font, I copied and pasted from my mail box.I'm visually impaired...not to a huge degree but it helps to use the large font.I believe you are right about the copyright on the imac stuff but if facebook decide otherwise, you have to reply electronically to their challenge.If you can't provide a reference directly from the copyright owner then they remove the video.I believe this is a programmed response and no human is involved which now makes it impossible for me to get my video uploading restored.They detect added soundtrack automatically and then challenge.There are many others in the same boat and facebook will not communicate.They have various discussion sites on which I have left messages including Mark Zuckerbergs own facebook but I don't think anyone from facebook ever reads them.I intend to start a second facebook which I can use purely to get my videos uploaded as a lot of my friends enjoy them BUT don't want fall foul of their programming again.If only iMac would put something on the net to this effect.I think it is so unfair that with modern technology it is impossible to contact these large conglomerates personally and receive an email response.I tried emailing [email protected] but I got a failure notice.If you have any ideas on how to get verification from apple direct, I would be very grateful.Thank You.

  • Managing more than one logical component in SMSY Current System Assignments

    Hi,
    I have a problem with managing logical components in TA SMSY in my Solution Manager System, in the section "System Groups and logical Components". I want to maintain more than one logical System e. g. from Type Application Server ABAP --> SAP NETWEAVER APPLICATION SERV.
    That means e. g. i want to maintain 2 or more Demo Systems from different Servers or Instances of the same Product Version in the same logical Component .
    What I want to know is, is there a way to display these logical components in tne  "Current System Assignments" - View in that form
    Logical Component is e.g. : SAP NETWEAVER APPLICATION SERV
    product/main instance is   : SAP NETWEAVER [Application Server ABAP]
    Product Version | Development System | Demo System | Training System | Production System | ...
    |--|||--
    |
    SAP NW 7.0        |                                         | ZB1: 100           |                               |                                     |
    |--|||--
    |
    SAP NW 7.0        |                                         | ZB2: 800           |                               |                                     | ...
    Thanks beforehand for your help.
    Greets C. Peifer
    Edited by: Carsten Peifer on Dec 15, 2008 4:03 PM

    Thanks for your quick answer,
    but i have to say, that this is not exactly what i've been lookin for.
    What I need in my System Landscape is to have each demosystem as a logical Component from the same type (e.g. SAP NETWEAVER APPLICATION SERVER ABAP).
    So that in Change Management in a Maintenance Optimizer Transaction i can choose between each demo system in my System Landscape (from the type SAP Netweaver Application Server ABAP) that i will maintain in Maintenance Optimizer, e.g. download a new SP Stack.
    My Intention is to create new logical components from type  SAP NETWEAVER APPLICATION SERVER ABAP in my Namespace e.g. ZSAPNW01, ZSAPNW02, ... and to maintain the types of systems (Demo, Development, Training etc ...) for each logical component.
    Is this the only Possibility?
    Or do i can also display my logical components the way i descriped beyond?
    >
    Product Version | Development System | Demo System | Training System | Production System | ...
    |--|||--
    |
    SAP NW 7.0 | | ZB1: 100 | | |
    |--|||--
    |
    SAP NW 7.0 | | ZB2: 800 | | | ...  

Maybe you are looking for

  • USB 6009 - mysterious problem

    Have mysterious problems with my new USB 6009. I'm using LabView 7 on MacOS-X 10.3.8. All vi's of DAQmx show "ERROR 15 - Ressource not found". Then I tested: - "lsdaq" shows the device - "nidatalogger" works - "mxbaseconfig" doesn't recocgnize it! I

  • Download problem

    I registered my Adobe purchase and have tried to download my free PDF portfolio templates, but I can't seem to download this. Does anyone have any suggestions?

  • Asset Query - Retirements

    Dear All Can you please help me out. I am creating a query in SAP to display asset transactional data and master data. I have encountered two issues. 1. I cannot find a field or table which shows the retirements value. This is available in the Asset

  • Altenate work centers in production order

    Hi, we have 2 different work cneters and any one work center can be selected in the prod order when we process. please advise how to create a routing that will allow to enter 2 work centers for one operation (alternate to each other) so that when we

  • Iphone 4 perdu

    J'ai perdu mon iphone , puis je le bloquer afin que celui qui l'a trouvé ne puisse pas l'utiliser ?