# Generalizing actions for a binary tree traversal?

• March 8th, 2013, 09:32 PM
Rectangle
Generalizing actions for a binary tree traversal?
I'm trying to find a way that I could take a binary tree class and traverse through it's nodes, performing X inline actions on each node without having to rewrite the same traversal code.
If Java allowed function pointers, this would be much simpler for me to write.

Basically, what I need is something like the following:
Code :

```public class BinaryTreeNode { public String identifier = ""; public BinaryTreeNode parent = null; public BinaryTreeNode left = null; public BinaryTreeNode right = null;   public BinaryTreeNode(BinaryTreeNode parent, String identifier) { this.parent = parent; this.identifier = identifier; }   public boolean isRoot() { return parent == null; }   public void inOrderTraversalFrom(BinaryTreeNode node, /* ??? */ actions) { if(node.left != null) inOrderTraversalFrom(node.left);   /* do something with "actions" here */   if(node.right != null) inOrderTraversalFrom(node.right); } }```
... where actions could allow for different methods to be performed, taking in a different set of parameters depending on the type of action(s) to be performed on each node.
How is this possible? What would be the most dynamic way to perform this?
• March 9th, 2013, 03:05 AM
Rectangle
Re: Generalizing actions for a binary tree traversal?
• March 11th, 2013, 08:40 AM
janpiel
Re: Generalizing actions for a binary tree traversal?
Take a look at this:
Code java:

``` public static interface IFunction<T> {   public void callFunction(T t);   }   private static IFunction<String> functionPointer = new IFunction<String>() {   @Override public void callFunction(String t) { System.out.println(t);   } };   public static final List<IFunction<?>> functions = new ArrayList<>();   { functions.add(functionPointer); }     public void inOrderTraversalFrom(BinaryTreeNode node, List<IFunction<?>> actions) { if(node.left != null) inOrderTraversalFrom(node.left, null);   IFunction<String> func = (IFunction<String>) actions.get(0);   func.callFunction("Hello function pointer");   if(node.right != null) inOrderTraversalFrom(node.right, null); }```

That's a quick and dirty solution but that's a kind of function pointing in java.

You can use generic parameter to change the parameters but you must declare parameter classes for each function signature.