CC-4 : Implement Breadth First Search in Binary Tree.
Description:
Implement and test a Breadth First Search in Binary Tree.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
To Search: 8 To Search: 28 |
8 Found? true 28 Found? false |
Pseudocode:
| The node data of Tree node to be searched will be provided as input parameter to the method. |
| Define a Queue to temporarily hold Tree nodes as we do Breadth First search. |
| Add the root node of the Tree to the Queue. |
| While Queue size is not zero:
Extract a Tree node from the Queue.
If data of current Tree node is same as the input node data parameter to be searched, return true.
If left child node of current Tree node is not null, add it to the Queue.
If right child node of current Tree node is not null, add it to the Queue.
|
| If we do not find the required node via above while loop then the required node is not present in the Binary Tree, so return false. |
Code:
public boolean bfsSearch(BinTreeNode root, int toSearch) throws Exception{
if (root==null) {return false;}
Queue<BinTreeNode> queue=new LinkedList<BinTreeNode>();
queue.offer(root);
BinTreeNode node=null;
while (queue.size()!=0) {
node=queue.poll();
if (node.getNodeData()==toSearch) {
return true;
}
if (node.getLeftChild()!=null) {
queue.offer(node.getLeftChild());
}
if (node.getRightChild()!=null) {
queue.offer(node.getRightChild());
}
}
return false;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |