Learn-dsa..in 30 days!



























CC-5 : Check if Binary Tree is balanced.

Description:

A Binary Tree is balanced if difference of height between left and right subtree of each node is either 0 or 1. Given an input Binary Tree, check if it is balanced.

Test cases and expected outputs:

Input Parameters Expected outputs

Balanced? true

Pseudocode:

Define a Boolean variable named balanced at the class level.

Method checkBalance(NodeTreeNode node):

Method checkBalance(NodeTreeNode node)
Define rightHeight=checkBalance(node.getRightChild()).
If difference of leftHeight and rightHeight is >=2, Binary Tree is not balanced, set balanced false.
If leftHeight > rightHeight return leftHeight from the method.
If rightHeight > leftHeight return rightHeight from the method.


Code:

{
	
private boolean balanced=true;
	
public boolean checkBalanced(BinTreeNode root) throws Exception{
	balanced=true;
	checkBalance(root);
	return balanced;
}
	
private int checkBalance(BinTreeNode node) {
	if (node==null) {return 0;}
	int leftHeight=checkBalance(node.getLeftChild())+1;
	int rightHeight=checkBalance(node.getRightChild())+1;
	if (Math.abs(leftHeight-rightHeight) >=2) {
		balanced=false;
	}
	if (leftHeight > rightHeight ) {
		return leftHeight; 
	}else {
		return rightHeight;
	}
}
}

Click here to download and run code and test cases !