Find the level of Deepest child Treenode

Sangram Nandkhile picture Sangram Nandkhile · Nov 29, 2011 · Viewed 7.2k times · Source

I have treenode & i would like to find the deepest child in the treenode. if there are 2 child nodes with level 11 & level 13 respectively then i need unction to return me the value 13.

How can i do that ?

public int FindLevel(TreeNode oParentNode)
{
   counter++;
  forech(TreeNode oSubNode in oParentNode.Nodes)
  {
    FindLevel(oParentNode);
  }

 return Counter;
}

Answer

Fischermaen picture Fischermaen · Nov 29, 2011

Here is my suggestion for you:

private int GetDeepestChildNodeLevel(TreeNode node)
{
    var subLevel = node.Nodes.Cast<TreeNode>().Select(GetDeepestChildNodeLevel);
    return subLevel.Count() == 0 ? 1 : subLevel.Max() + 1;
}

here with explicit types:

private int GetDeepestChildNodeLevel(TreeNode node)
{
    var subLevel = node.Nodes.Cast<TreeNode>().Select<TreeNode, int>(subNode => GetDeepestChildNodeLevel(subNode));
    return subLevel.Count<int>() == 0 ? 1 : subLevel.Max() + 1;
}