Question
Scenario Implement an algorithm that searches the binary tree one level at a time, left to right. The traversal starts from the root node and
Scenario
Implement an algorithm that searches the binary tree one level at a time, left to right. The traversal starts from the root node and finishes at the leaf node.
Apply BFS traversal in Java.
Steps for Completion
- Implement the psuedocode algorithm from Snippet 3.14 (shown below) in a public method called printBfs()in SimpleBinaryTree. The return value should be void and it should print each node on a newline.
breadthFirstSearch(root) if (root != null) queue = createQueue() enqueue(queue, root) while (not isEmpty(queue)) node = dequeue(queue) process(node) if(node.left != null) enqueue(queue, node.left) if(node.right != null) enqueue(queue, node.right)
Snippet 3.14
Tasks
Implement the BFS algorithm in the printBfs() method.
Output values were not hard coded into the program.
Code given:
import java.util.LinkedList; import java.util.Optional; import java.util.Queue;
public class SimpleBinaryTree
public void put(K key, V value) { if (root == null) root = new BinaryTreeNode<>(key, value); else put(key, value, root); }
private void put(K key, V value, BinaryTreeNode
public Optional
private Optional
public Optional
protected K minKey(BinaryTreeNode
public void printBfs() { // write your code here }
public void printDfs() { Optional.ofNullable(root).ifPresent(this::printDfs); }
private void printDfs(BinaryTreeNode
public static void main(String[] args) { SimpleBinaryTree
System.out.println(binaryTree.get(457998224)); System.out.println(binaryTree.get(366112467)); System.out.println(binaryTree.get(671031776)); System.out.println(binaryTree.get(225198452)); System.out.println(binaryTree.get(419274013)); System.out.println(binaryTree.get(751965387));
binaryTree.put(751965387, "Sam");
System.out.println(binaryTree.get(751965387)); System.out.println(binaryTree.get(999999999)); System.out.println(binaryTree.minKey());
binaryTree.printDfs(); binaryTree.printBfs(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started