Problem: The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Approach: Use preorder traversal.
public int MinDepth()
{
if (this.Root == null)
{
return 0;
}
int minDepth = int.MaxValue, currDepth = 1;
this.MinDepth(this.Root, currDepth, ref minDepth);
return minDepth;
}
private void MinDepth(BinaryTreeNode node, int currDepth, ref int minDepth)
{
if (node == null)
{
return;
}
if (node.LeftNode == null && node.RightNode == null)
{
if (minDepth > currDepth)
{
minDepth = currDepth;
}
return;
}
this.MinDepth(node.LeftNode, currDepth + 1, ref minDepth);
this.MinDepth(node.RightNode, currDepth + 1, ref minDepth);
}
No comments:
Post a Comment