-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadth first search in tree(Iterative).java
More file actions
46 lines (45 loc) · 1.07 KB
/
Breadth first search in tree(Iterative).java
File metadata and controls
46 lines (45 loc) · 1.07 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
//edit this code
import java.util.*;
class Node{
int data;
Node left,right;
Node(int value){
data=value;
left=right=null;
}
}
class Tree{
Node root;
Tree(){
root=null;
}
void bfstree(){
Queue<Node> q=new LinkedList<>();
q.add(root);
while (!q.isEmpty()){
Node temp=q.peek();
q.remove();
System.out.print(temp.data+" ");
if(temp.left!=null){
q.add(temp.left);
}
if(temp.right!=null){
q.add(temp.right);
}
}
}
}
public class BFSIterative {
public static void main(String[] args) {
Tree tree = new Tree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.left.left.right = new Node(6);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(8);
tree.bfstree(tree.root);
}
}