karthik
karthik

Reputation: 473

Recursive function call conversion to lambda expression in Tree Implementation java

I took a case study for learning lambda expression of java 8 which is Generic N-array Tree Implementation.I have a recursive function to get the total number of nodes present in the tree.I am struck at this point.

public class GenericTree<T> {

private GenericTreeNode<T> root;

public GenericTree() {
    super();
}

public GenericTreeNode<T> getRoot() {
    return this.root;
}

public void setRoot(GenericTreeNode<T> root) {
    this.root = root;
}

public int getNumberOfNodes() {
    int numberOfNodes = 0;

    if(root != null) {
        numberOfNodes = getNumberOfnodeRecursiveFunc(root) + 1; //1 for the root!
    }        

    return numberOfNodes;
}

private int getNumberOfnodeRecursiveFunc(GenericTreeNode<T> node) {
    Integer numberOfNodes = node.getNumberOfChildren();

    for(GenericTreeNode<T> child : node.getChildren()) {
        numberOfNodes += getNumberOfnodeRecursiveFunc(child);
    }        

    //node.getChildren().stream().map(child ->this.getNumberOfnodeRecursiveFunc(child));

    //return node.getNumberOfChildren() + node.getChildren().stream().collect(Collectors.summingInt(GenericTree::getNumberOfnodeRecursiveFunc));        
}}

How to use lambda expression recursively to get the number of nodes instead of using the conventional approach mentioned in the code snippet?

Note : I went through multiple other questions,they provide simple factorial expression.So please provide some deeper insight on this

Upvotes: 1

Views: 380

Answers (1)

acontell
acontell

Reputation: 6922

Assuming your question is how to "translate" getNumberOfnodeRecursiveFunc to lambdas (the code seems correct so I guess it's what you're asking), a possible solution could be:

private int getNumberOfnodeRecursiveFunc(GenericTreeNode<T> node) {
        return node.getNumberOfChildren() + node.getChildren().stream().collect(Collectors.summingInt(Test::getNumberOfnodeRecursiveFunc));
    }

You'd have to change Test to the appropriate name of the class in order to make the method reference work.

You use collect to make the reduction and get the number of nodes in the tree.

I guess it would be enough.

UPDATE

To solve the compiler error, you can try two approaches:

  • making the getNumberOfnodeRecursiveFunc static (I guess isn't an option)
  • Substitute the method reference by a lambda.

    private int getNumberOfnodeRecursiveFunc(MyNode node) {
      return node.getNumberOfChildren() + node.getChildren().stream().collect(Collectors.summingInt(n - > getNumberOfnodeRecursiveFunc(n)));
    }
    

Upvotes: 1

Related Questions