Learn-dsa..in 30 days!



























CC-3 : Implement Breadth First Traversal of Binary Tree using recursion.

Description:

Implement and test a Breadth First Traversal of Binary Tree using recursion.

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.

Method bfs():

Call method maxLevel() to find the maximum depth of the Binary Tree.
Iterate through each level of the Binary Tree using for loop
Call method bfsLevelwise with root node of Binary tree and current level

Method bfsLevelwise(root,lvl):

If lvl=1, add data of root node to Breadth First traversal arraylist.
Else:
bfsLevelwise(root.getLeftChild(), lvl-1).
bfsLevelwise(root.getRightChild(), lvl-1).

Method maxLevel(root)::

Set leftLevel=maxLevel(root.getLeftChild()).
Set rtLevel=maxLevel(root.getRightChild()).
If (leftLevel > rtLevel) return leftLevel+1.
If (rtLevel > leftLevel) return rtLevel+1.


Code:

public class BinTreeBfsRecursive {

private ArrayList<Integer> bfsTraversal=new ArrayList<Integer>();
public ArrayList<Integer> getBfs() {
	return bfsTraversal;
}
public void setBfs(ArrayList<Integer> bfsTraversal) {
	this.bfsTraversal = bfsTraversal;
}

public void bfs(BinTreeNode root) {
	int maxlevel= maxLevel(root);
	for (int lvl=1; lvl<=maxlevel; lvl++) {
		bfsLevelwise(root, lvl);
	}
}

public void bfsLevelwise(BinTreeNode root, int lvl) {
	if (root==null) {return;}
	if (lvl==1) {
		bfsTraversal.add(root.getNodeData());		
	}else {
		bfsLevelwise(root.getLeftChild(), lvl-1);
		bfsLevelwise(root.getRightChild(), lvl-1);
	}
}

public int maxLevel(BinTreeNode root) {
	if (root==null) {return 0;}
	else {
		int leftLevel=maxLevel(root.getLeftChild());
		int rtLevel=maxLevel(root.getRightChild());
		if(leftLevel > rtLevel) {
			return leftLevel+1;
		}else {
			return rtLevel+1;
		}		
	}
}
}

Click here to download and run code and test cases !