Solution
getNode(currentNode.right, name);
You call the getNode(...)
method but you don't do anything with it.
A better solution
If you are willing to use googles Guava (must-have for every project in my opinion) and java 8, you can do the following:
public static final Traverser<Node> TREE_TRAVERSER =
Traverser.forTree((SuccessorsFunction<Node>) node ->
Stream.of(node.right, node.left)
.filter(Objects::nonNull)
.collect(Collectors.toList()));
And then call it where ever you want to traverse the tree:
for (Node n : TREE_TRAVERSER.depthFirstPreOrder(root)) {
if (n.getName().equals("foo")) {
// todo: do stuff with node foo
}
}
The java 8 way of traversing the tree would then be:
Iterable<Node> nodes = TREE_TRAVERSER.depthFirstPreOrder(root);
Optional<Node> result = StreamSupport.stream(nodes.spliterator(), false)
.filter(n -> n.getName().equals("foo")) // find node with name "foo"
.findAny(); // we assume there is <= 1 node, so we take any.
// node.isPresent() to check if you found a Node and result.get() to get the Node
How does this work?
Well, Guava has this nice class called a Traverser<N>
. You just give it one parameter, which is the SuccessorsFunction<N>
. It takes any object N
and returns a Iterable<? extends N>
, which are the child nodes.
We use Stream
s to do this. First we create a Stream
of the two child nodes. We then filter them to only have a Stream
of nonNull
Node
s and collect them in a List
(since the SuccessorsFunction<Node>
wants to return a Iterable<Node>
).
This Traverser<N>
only has to be created once, so we made it public static final
. You can now choose an iteration order. We chose depthFirstPreOrder
, which returns an Iterable<N>
we can iterate over
If you haven't heard of Stream
s before, I would recommend this turorial.