Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 its nodes,
performing X amount of inline actions on each node without having to rewrite the same traversal code over and over again.
I'd imagine if Java allowed function pointers, this would be much simpler for me to figure out...

Basically, what I need is something like the following:

public class BinaryTreeNode {

    //...

    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.

A good example of this would be a class which is meant to draw these nodes could be passed, accepting a Graphics object as one of it's parameters, versus a class which is meant to perform some other series of actions which wouldn't require a Graphics object as a parameter, but a completely different set of parameters instead.

How is this possible? What would be the most dynamic way to perform this?

like image 826
RectangleEquals Avatar asked Nov 04 '22 02:11

RectangleEquals


1 Answers

One way to do it would be:

action could be an instance of a class that receives a Node and applies the Action to it:

public interface Action{
  public void apply(Node node){
  // To be done in the classes that will implement 
  // this interface. If it's a graphic-display of the nodes, the apply 
  // method will call draw(node.value), for example
  }
}

The line:

/* do something with "actions" here */

should be replaced with

action.apply(node);

The signature of the method should be changed to:

public void inOrderTraversalFrom(BinaryTreeNode node, Action action)

and the recursive call should be:

inOrderTraversalFrom(node.left, action);
like image 65
Nir Alfasi Avatar answered Nov 14 '22 23:11

Nir Alfasi