-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay23-BST-Level-Order-Traversal
More file actions
38 lines (27 loc) · 1.1 KB
/
Day23-BST-Level-Order-Traversal
File metadata and controls
38 lines (27 loc) · 1.1 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
Problem:
Objective
Today, we're going further with Binary Search Trees. Check out the Tutorial tab for learning materials and an instructional video!
Task
A level-order traversal, also known as a breadth-first search, visits each level of a tree's nodes from left to right, top to bottom.
You are given a pointer, root, pointing to the root of a binary search tree. Complete the levelOrder function provided
in your editor so that it prints the level-order traversal of the binary search tree.
Hint: You'll find a queue helpful in completing this challenge.
Solution:
static void levelOrder(Node root){
//Write your code here
if (root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(node.data+" ");
if (node.left != null) {
nodes.add(node.left);
}
if (node.right!= null) {
nodes.add(node.right);
}
}
}