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!
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, 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 AMHi,
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... -
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. -
How to do complex file search for "word" unknown characters "word" .file extension?
How to do complex file search for "word" unknown characters "word" .file extension?
Using spotlight in Finder helps. Do you know how to search for files in Finder?
-
How do I run a search for all photos on my iMAc?
How do I run a search for all photos on my iMAc?
Looking for something like search assistant...
actually on an Ext Hard drive.open a finder window by clicking on mr. smiley face and then click on ALL PHOTO's on the bottom right
-
How to extend the time line for the premiere on mac pro mavericks
how to extend the time line for the premiere on mac pro mavericks
Wrong place.
Try the Adobe Premiere forum.
http://forums.adobe.com/community/premiere
Good luck,
x -
How to extend the costing view for a material
How to extend the costing view for a material
Use MM01 Trxn code and Select Material and Select Costing Views and Maintain, Save it.
Else Use MM50 and Select Material and Mainenance Status as G Costing and Execute, Maintain & Save. -
How to extend AVK to scan for other vendor-specific APIs?
All--
How do I extend AVK to scan for other vendor specific APIs.
I tried adding another <name> element underneath the
appropriate the <unsupported> tag in the asmt-config.xml file,
e.g.
<websphere50>
<supported>
</supported>
<unsupported>
<name>com.ibm.ws.activity.ActivityConstants</name>
.......... other <name> elements were left alone ..........
</unsupported>
</websphere50>
But when I scanned the source code it didn't find an import of that API.
Note: it did find an import of the APIs that were pre-defined in the asmt-
config file; just not the one that I added.
Is adding a <name> to the asmt-config.xml file the right approach?
If so, how does the SourceScan ant task know where to find the asmt-
config.xml file. Currently, I left it in the %JAVKE_HOME%/config folder.
Is that the right place for that file?
Any comments on how to extend AVK to scan for other vendor
specific APIs would be greatly appreciated.Oops!
Its probably bad form to answer your own question, but after
sending out the original post, I treid:
1. opening a new shell
2. running the %JAVKE_HOME%/bin/javke_setenv.bat
3. then ran the "asant code-scan" from that shell and viola it worked ...
Sorry for any confusion. -
TS1398 iPhone can't search for wireless networks. Any suggestions?
My iphone 4S displays a message saying that it, "Can not search for wireless networks. Any suggestions? I've turned it off, reset the network settings, taken out the sim card, turned on/off airplane mode . . . what else can I do? When I've phoned the help line I've been waiting to get through for over an hour!!
Try Resetting Network Settings from Settings > General Reset.
If that doesn't do it, this Apple doc might have something helpful -> iOS: Troubleshooting Wi-Fi networks and connections -
Report for the material having any kind of block
Dear All
I would like to have a report for the material having any kind of block i.e.(X-plant matl status OR Plant-sp.matl status).
Pl suggest any standard report or through table.
Rregards
ManojHi
Trnx. SE16 Table MARA
fields
MSTAE X-plant matl status
MSTAV X-distr.chain status
Vishal... -
Like i stated i'm having a problem with every time i type into a search bar or box of any kind including log ins and such the box turns blue, and in many cases makes it so i can not read what i am typing. Tried same website on IE and they worked fine so i assume it's firefox, is there anything i can do about it
For me, the google search bar turns blue once I've typed in a search term, but then want to click on it again to change or add something. The entire bar turns blue. I can still type, but it's hidden. Then when I click Search, it does bring up my search results and now the terms I've written are showing in the search bar, with no blue.
The only way to get out of it when the blue is there, is to reload the page. -
Hello, I am running a Mac book pro soft. 10.5.8 version. Since June the current year I did not get any updates for the software or any kinds of the other application, in my opinion that's weird for such a company.
The problem that I have now is with the Iphone 5 which is not supported for the current Itunes and I can not download the Itunes 10.7 version. What I supposed to do in this case because I can not syncronize at all.
Please give me a hand as soon as possible.
Many thanksMac OS X 10.5.8 is years old, 3 major versions out-of-date and unsupported at this point. You will never get any further updates for 10.5.8, and more and more applications will stop supporting 10.5.8 as time goes on. As mende1 points out, you can buy Snow Leopard (Mac OS X 10.6), which will let you use your new iPhone with your computer, but you need to make sure your computer's hardware is supported. See the system requirements for Snow Leopard:
http://support.apple.com/kb/SP575
If your computer cannot run Snow Leopard, you will need to either buy a new computer or abandon any thoughts of syncing the iPhone with that computer.
Also, note that you'll get far better integration of your iPhone and your Mac if you're using Lion (Mac OS X 10.7) or Mountain Lion (Mac OS X 10.8), which are required to use iCloud. Of course, the requirements of those systems are even steeper than those of Snow Leopard:
http://support.apple.com/kb/HT4949
http://support.apple.com/kb/HT5444 -
How do you do a search for multiple occurences of the same word in a NOTE?
How do you search for multiiple occurences of a word in NOTES? I seem only to be able to find the first occurence and then it goes into a loop, never past the first occurence.
I want to find all the same words in ONE NOTE. It is a very loong list and I want to find all cccurences of a specific word in that one NOTE when I do a search. I thought I had solved this earlier today but now I can't seem to repeat it. I type in word in the SEARCH box, select the NOTE and then it shows me the FIRST occurence in that note, but only the first,
Maybe you are looking for
-
Xslt: mapping different elements onto instances of an unbounded element
How can you map different elements onto sequential elements of an unbounded type? For example: <record> <tag1>abc</tag1> <tag2>def</tag2> <tag3>ghi</tag3> </record> onto <properties> <property name="tag1" seq="1">abc</property> <property name="tag2"
-
2 iMacs sharing a Firewire Drive
Is is possible to have my 2 iMacs share the same external Firewire drive via Firewire? I have an ethernet hub but it's not quite fast enough for what I need. I want both iMacs using the same hard drive thru firewire... thanks
-
I'm having trouble laying out the form in the way I would like. Is there a way to change the form to allow different spacing between elements? Also, is there a way to disable 'left allign' on text elements from affecting the whole page? It is playing
-
Where is the task bar on safari on ipad?
I just got my New Ipad... where is the task bar on safari I have no task bar?
-
Why my macbook air 's fan makes noise while i am watching movies online?
is it normal?