-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevelOrderTraversal.java
More file actions
85 lines (74 loc) · 1.92 KB
/
LevelOrderTraversal.java
File metadata and controls
85 lines (74 loc) · 1.92 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package CodingPatterns.TreeBFS;
import java.util.LinkedList;
import java.util.Queue;
/**
* To implement a Binary Tree Level Order Traversal in Java,
* you can use a breadth-first search (BFS) approach,
* which utilizes a queue to traverse the tree level by level.
* Here's the step-by-step guide and the implementation:.
*/
public class LevelOrderTraversal {
/**
* The type Tree node.
*/
static class TreeNode {
/**
* The Value.
*/
int value;
/**
* The Left.
*/
TreeNode left;
/**
* The Right.
*/
TreeNode right;
/**
* Instantiates a new Tree node.
*
* @param value the value
*/
TreeNode(int value) {
this.value = value;
}
}
/**
* Level order traversal.
*
* @param root the root
*/
public static void levelOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
System.out.print(node.value + " ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
levelOrderTraversal(root);
}
}