This is a continuation of my post How to create the binary tree in c#.In this post, I will show you how to calculate the max depth of a given binary tree in c#.
max depth of a tree – the number of nodes along the longest path from the root node down to the farthest leaf node.
public int MaxDepth()
{
return MaxDepth(_root);
}
private int MaxDepth(Node root)
{
if (root == null)
return -1;
// compute the depth of each subtree
else
{
int leftDepth = MaxDepth(root.Left);
int rightDepth = MaxDepth(root.Right);
//Return max of left or right tree.
return 1 + Math.Max(leftDepth, rightDepth);
}
}