Learn-dsa..in 30 days!



























CC-16 : Find Diameter of Binary Tree.

Description:

Diameter of a Binary Tree is path with maximum count of edges between two Tree Nodes. Given a Binary Tree, find and return the Diameter of the Tree.

Test cases and expected outputs:

Input Parameters Expected outputs
Find diameter of above tree. Max Diameter: 8

Pseudocode:

Initialize a variable maximumDistance to hold the diameter.

Method findMaxDiameter():

Call updateMaxDistance().
Return maximumDistance.

Method updateMaxDistance (TreeNode):

If TreeNode is null return 0.
Set leftDepth by calling updateMaxDistanc() with TreeNode’s left child.
Set rightDepth by calling updateMaxDistanc() with TreeNode’s right child.
Set currentMaxDistance to (leftDepth + rightDepth).
If (currentMaxDistance > maximumDistance) set maximumDistance to currentMaxDistance.
Initialize a variable currentMaxDepth of type integer.
If leftDepth > rightDepth, set currentMaxDepth= leftDepth.
If rightDepth > leftDepth, set currentMaxDepth= rightDepth.
Return currenMaxDepth+1.


Code:

public class BinTreeMaxDiameter {
	
private int maxDistanceBetween2Nodes=0;

public int finddMaxDiameter(BinTreeNode root) {
	updateMaxDistance(root);
	return maxDistanceBetween2Nodes;
}

public int updateMaxDistance(BinTreeNode node) {
	if (node==null) {
		return 0;
	}
	int leftMaxDepth=updateMaxDistance(node.getLeftChild());
	int rightMaxDepth=updateMaxDistance(node.getRightChild());
	int currenMaxDistance=leftMaxDepth+rightMaxDepth;
	if (currenMaxDistance > maxDistanceBetween2Nodes ) {
		maxDistanceBetween2Nodes=currenMaxDistance;
	}
	int currenMaxDepth=0;
	if (leftMaxDepth >rightMaxDepth ) {
		currenMaxDepth=leftMaxDepth;
	}else {
		currenMaxDepth=rightMaxDepth;
	}
	return currenMaxDepth+1;
}
}

Click here to download and run code and test cases !