r/javahelp • u/TauPixel • Jan 14 '20
Recursion with Lambda Expressions
Hello everyone!
I'm having a bit of trouble understanding the lambda expressions. My code snippet should be using a position of a tree and do the traversal with the code. I think I might be looking it at the wrong way. Maybe logic or lack of syntax knowledge of the lambda expressions is what's stopping me of doing what I want.
Any help would be greatly appreciated. Below my code snippet:
@Override
public void traverseInOrder(Consumer<Position<E>> visit) {
visit = p -> {
inOrder(p);
};
visit.accept(root);
}
private void inOrder(Position<E> p) throws InvalidPositionException {
BinaryTreeNode<E> t = (BinaryTreeNode<E>) p;
pt -> {
inOrder(t.left);
System.out.println(t.element());
inOrder(t.right));
};
}
16
Upvotes
2
u/Roachmeister Java Dev Jan 15 '20
Well, one thing strikes me as wrong right off the bat. As an example, suppose you had the following method:
See the problem? I ignore the parameter that is passed in and just print "hello" every time. That's essentially what you're doing in your
traverseInOrdermethod.Instead, you need to call
traverseInOrderwith the lambda: