Given this Class that represents a tree , i got a little confused on how would i return a list that will consist of nodes that are part of the tree's height .
public class TreeNode<T>
{
private T m_Data;
public T Data
{
get
{
return m_Data;
}
set
{
m_Data = value;
}
}
private readonly List<TreeNode<T>> m_Children;
public List<TreeNode<T>> Children
{
get
{
return m_Children;
}
}
public TreeNode(T i_Data)
{
this.m_Data = i_Data;
m_Children = new List<TreeNode<T>>();
}
public void AddChild(T data)
{
m_Children.Add(new TreeNode<T>(data));
// return m_Children[m_Children.Count-1];
}
public List<T> LongestPathNodes(TreeNode<T> i_node)//this function
{
if(i_node.m_Children.Count == 0)
{
List<T> choosenMove = new List<T>(1);
choosenMove.Add(i_node.Data);
return choosenMove;
}
else
{
foreach(TreeNode<T> treeNode in i_node.Children)
{
}
}
}
The function which i'm talking about is the "LongestPathNodes" Function ,I think it has to be recursive , i wrote part of it but i'm confused on how should i proceed , given the fact that the tree does not have to be a binary one .
Define a
Height
property:Now you can return the nodes of the longest branch from any given node:
If you need this as a
List<T>
it is a LINQ one-liner: