views:

154

answers:

1

I have a binary tree of functions and terminal values. I'd like to print this tree as a lisp statement would be represented!

For example, a tree with just a root of "+" and terminals of "2" and 4" would read (+ (2 4)).

+1  A: 

You need to do an preorder traversal of the binary tree. So if you have the tree:

      +
  5       -
        3   2

You would want to visit +, 5, -, 3, 2, in that order. You can do this recursively as follows (assuming your nodes have the fields value, left, and right):

  public void preorder() {
    if (leaf == null && right == null) 
      System.out.println(value);
    else {
      System.out.println("(");
      System.out.println(value);
      if(left != null) left.preorder();
      if(right != null) right.preorder();
      System.out.println(")");
    }
  }

Notice that you simply visit the current node, then the left child, then the right child.

Justin Ardini