Functionally traversing a tree in C#

后端 未结 3 1667
野性不改
野性不改 2021-01-02 19:42

Consider the following extension method in c#, Traverse:

IEnumerable Traverse( this IEnumerable source, 
                                  


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 19:57

    Well I don't think you can avoid searching the tree until you find the node you're looking for without storing a parent pointer.

    You'll start from the root. Test the current node for a match. If it is a match, return the node or just the name (as a list of this one element). Otherwise, if this is a leaf node, return null. If not a leaf, traverse it's children and if the children return non-null value, prepend the current node to your list and return that.

    Returning from the original call, null means no match found. Otherwise you'll have your list of nodes in order.

提交回复
热议问题