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...
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. -
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. -
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
*/Thankssunnymanman 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,
DimavaIt'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. -
UCCX 9 Search by first 4 letters and another data
Good afternoon everyone
Could you please advise me on this question? I need to search a person's information by using first 4 of ID number, first 3 of area code and another data such as his/ her birthday...
My script is....
1. Ask a caller to enter first 4 digit of ID (Complete ID number is 10digits or longer)
2. Ask a caller to enter first 3 numbers of area code
3. then, ask his/her to enter complete birthday (MM/DD/YYYY)
4. With those information, I need database to search person's recent activity data
I tired for first 4 digit ID search as SELECT * From VW_Database WHERE CustomeNumb LIKE 'CustomerNumber%' in DB Read Field Selection. However, it comes back as no data found... It does not look like taking wild card (%)
Please advise how i can use wildcards with this data search....
Thank you ,
NanaThank you so much for super quick reply.
My team member Left function LEFT (CsuomterNum, 4) = $CustomerNumber and yes, it worked
Thank YOU for your help as usual!!!!
nana -
Select-String to search only first column in .CSV
Hello all,
I'm wondering if anyone knows a way to only search the first column of a .CSV file using Select-String. I guess I could probably import-csv and pipe the first column to select-string, but I was wondering if Select-string has this capability within itself?Yes, a "large file that I only need a few lines from" is more the issue. And I was also just curious if Select-String had such functionality. For the file I am reading, it has over 23,000 lines (13MB), and there is a significant
performance increase with using select-string (over %4000 increase) :
Using Import-CSV and Where-Object: around 5.938 seconds
Using Select-String: around 0.138 seconds
Thus, if I have several strings that I want to search the file for, I would prefer to use Select-String. I suppose I could just do the following?
1. Use Select-string to search the file for each string I need to search for
2. Once I'm done searching for all strings, I can query the resultant data set to be sure the string is in the first column of each record in the dataset
3. If the string is not in the first column in the resultant data set, I can just remove the record.
Am I way off base here? -
C2-01-Contact Search using First Name
Hello,
Could someone please advise me on how to set the phone to show Contact/Names on first name basis. Currently it was set to Last Name, so whenever I seach I need to search last name.
My old phone allows me search on first name basis but I can no longer find the setting on C2-01.
You advise would be appreciated.
Thanks in advance.great.!!!! But the search result is having a company partner.
Why is it empty most of the time even a company partner is maintained.
And let me ask about customer contact - account management and contact- -
For this, the company partner is always empty.
Thkx
mike -
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. -
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. -
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. -
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
nullI 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.
} -
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 -
How to remove default search button in search module
I am a neophyte with code and css and normally work with Muse. But I am currently trying to customize the appearance of the search module so that it works with the website it will be serving. I have accomplished a large part of what I've been attempting, but have hit a snag in removing the default search button (CAT_Search). I've placed the image I want to use no problem, but it is contained in some weird gray beveled box with the original 'Search' text overlapping my image.
I have been making the rounds of tech support, tutorials, and every documented article on the search module and can find nothing that address this specific issue. Any help would be greatly appreciated! I am enclosing the what I've done so far below.
Thanks!
Paula
<style type="text/css">
body form {
width: 163px;
height: 48px;
form-top-right-radius: 5px;
form-bottom-right-radius: 5px;
background-image: url(http://corehog.businesscatalyst.com/images/search.png);
.search-box {
color: #999966;
font-family: lato;
font-style: normal;
font-weight: 100;
width: 86px;
height: 24px;
border: none;
max-width: 86px;
opacity: 0%;
max-height: 24px;
margin-left: 12px;
margin-top: 12px;
margin-bottom: 12px;
.cat_button {
width: 32px;
height: 24px;
border: none
background-color: none;
background-image: url(http://corehog.businesscatalyst.com/images/search-button.png);
margin-left: 12px;
margin-top: 12px;
margin-right: 20px;
margin-bottom: 12px;
</style>
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.--><script>var __adobewebfontsappname__="dreamweaver"</script><script src="http://use.edgefonts.net/lato:n1:default.js" type="text/javascript"></script>
<form name="catsearchform87352" method="post" action="/Default.aspx?SiteSearchID=3752&PageID=/http://corehog.businesscatalyst.com/search-results.html"><div><input class="search-box" type="text" name="CAT_Search" id="CAT_Search" /><input class="cat_button" type="submit" value="Search" /></div></form>
{module_searchresults}Hi Ramandeep Nanda,
Thanks for the reply.
I followed a slightly different approach than the one mentioned in your post.
I have not used any client side javascript attributes.I got the inputListOfValues Component from the launch listener event ( launchPopupEvent.getComponent() ) and in the launch listener i am setting richQuery.setModeChangeVisible(false);
It is hiding the button now but only for the first invocation of the search dialog, it is not working.
More specifically, for the first invocation of the search dialog, Iterator facetNames = inputListOfValues.getFacetNames(); is not returning the child components and hence the button is not being hidden.
Any idea why this might be happening?
Thanks,
Vikas
Maybe you are looking for
-
Hi We´re having some serious issues with editing timelapses in Lightroom (5.6). What seems to happen over and over again, is that if there´s a small change within the frame (such as a bird flying past, people walking), the editing result varies great
-
Hi All, Need expertise help to resolve the issue I am getting with Oracle Report builder. I have installed and configured Oracle Forms and Reports Builder 11g on my Windows 7 & 64 bit machine. Oracle Forms are working fine and I am getting an error
-
About physical standby database
We have physical standby database(10g). what are steps to put standby database in ready only mode for time being and then put it back in primary-secondary relationship once cheking is done?
-
AS in frame 1 of a linked swf executes, sometimes-
I'm using the loader class to load an external swf and attach it to an empty movie clip, the final step follows: function loadComplete(e:Event):void { mc_launch.addChild(gLoader); MovieClip(gLoader.content).gotoAndPlay("start"); When naviga
-
Weblogic Error on settings update & deployments: FileNotFound config_bak
Hiyas, I am having a problem with WebLogic 10.3 where I keep getting the following error message when trying to deploy applications or update configurations in the console: An error occurred during activation of changes, please see the log for detail