CC-2 : Implement Breadth First traversal of Binary Tree.
Description:
Implement and test a Breadth First Traversal of Binary Tree (using iterative method).
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
|
|
Bfs traversal : 4, 5 ,7, 6, 78, 14, 33, 8, 16, 18, 9 |
Pseudocode:
| Define an ArrayList to hold the nodes traversed while doing Breadth First traversal. |
| Define a Queue to temporarily hold Tree nodes as we do Breadth First traversal. |
| Add the root node of the Tree to the Queue. |
| While Queue size is not zero:
Extract a Tree node from the Queue.
Add the data of the current Tree node to the ArrayList.
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.
|
| Return the Array list as it contains the data of the nodes of the Tree in Breadth First order. |
Code:
public ArrayList<Integer> bfsTraversal(BinTreeNode root) throws Exception{
if (root==null) {return null;}
ArrayList<Integer> bfs=new ArrayList<Integer>();
Queue<BinTreeNode> queue=new LinkedList<BinTreeNode>();
queue.offer(root);
BinTreeNode node=null;
while (queue.size()!=0) {
node=queue.poll();
bfs.add(node.getNodeData());
if (node.getLeftChild()!=null) {
queue.offer(node.getLeftChild());
}
if (node.getRightChild()!=null) {
queue.offer(node.getRightChild());
}
}
return bfs;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |