Return the list of items which are part of the longest path from Tree's root to a Leaf in a General Tree

213 Views Asked by At

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 .

1

There are 1 best solutions below

2
On

Define a Height property:

public int Height =>
    m_Children != null && m_Children.Any()
    ? m_Children.Max(x => x.Height) + 1
    : 1;

Now you can return the nodes of the longest branch from any given node:

public IEnumerable<TreeNode<T>> LongestPathNodes()
{
    yield return this;
    var children = m_Children?
        .OrderByDescending(x => x.Height)
        .FirstOrDefault()?
        .LongestPathNodes();
    if (children != null)
    {
        foreach (var child in children) yield return child;
    }
}

If you need this as a List<T> it is a LINQ one-liner:

var list = node.LongestPathNodes().Select(x => x.m__Data).ToList();