forked from sambit77/Algoexpert-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearch.java
More file actions
57 lines (42 loc) · 1.11 KB
/
BreadthFirstSearch.java
File metadata and controls
57 lines (42 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;
class Tree
{
//Runs in O(V+E) time and O(V) Space
public static ArrayList<Character> breadthFirstSearch(Node root)
{
Queue<Character> q = new LinkedList<Character>();
q.add(root);
ArrayList<Character> LOTraversal = new ArrayList<Character>();
while(!q.isEmpty())
{
Node current = q.poll();
LOTraversal.add(root.data);
//add the all childs of current node to queue
// q.add(all childs of current node)
}
return LOTraversal;
}
class Node
{
public Node(char data)
{
char data;
ArrayList<Character> childs = new ArrayList<Character>();
}
}
Node root;
public static void add(Node root,Node addingPosition,char value)
{
if(root == null)
{
root = new Node(value);
return;
}
}
public static void main(String[] args)
{
//pass a graph/tree as argument where nodes are named as charcters
ArrayList<Character> al = breadthFirstSearch(root);
System.out.println(al.toString()); //PRints the array List Level order traversal
}
}