Recursive lambda expression to traverse a tree in C#

后端 未结 4 1227
萌比男神i
萌比男神i 2020-12-04 10:35

Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.

4条回答
  •  天命终不由人
    2020-12-04 11:07

    A proper solution, and indeed the idiomatic solution in many functional programming languages, would be the use of a fixed-point combinator. In a nutshell: a fixed-point combinator answers the question “how do I define an anonymous function to be recursive?”. But the solution is so nontrivial that whole articles are written to explain them.

    A simple, pragmatic alternative is to “go back in time” to the antics of C: declaration before definition. Try the following (the “factorial” function):

    Func fact = null;
    fact = x => (x == 0) ? 1 : x * fact(x - 1);
    

    Works like a charm.

    Or, for a pre-order tree traversal on an object of class TreeNode which implements IEnumerable appropriately to go over its children:

    Action> preorderTraverse = null;
    preorderTraverse = (node, action) => {
        action(node);
        foreach (var child in node) preorderTraverse(child, action);
    };
    

提交回复
热议问题