1
\$\begingroup\$

I implemented a recursive depth-first traversal, with all three traversal modes in this function. Is this the most succinct way to write the code?

/**
 * Node
 */
public class Node {
  private int value;
  Node left;
  Node right;

  public Node(int value) {
    this.setValue(value);
    left = null;
    right = null;
  }

  /**
   * @return the value
   */
  public int getValue() {
    return value;
  }

  /**
   * @param value the value to set
   */
  public void setValue(int value) {
    this.value = value;
  }

/**
 * Depth-First Traversal (Recursion)
 * @param root root of node-tree to be traversed
 */
public void dftRecursion(Node root) {
    if (root == null) {
      return;
    }
    switch (tMode) { // traversal mode
    case IN_ORDER:
      dftRecursion(root.left);
      System.out.print(root.getValue() + " ");
      dftRecursion(root.right);
      break;
    case PRE_ORDER:
      System.out.print(root.getValue() + " ");
      dftRecursion(root.left);
      dftRecursion(root.right);
      break;
    case POST_ORDER:
      dftRecursion(root.left);
      dftRecursion(root.right);
      System.out.print(root.getValue() + " ");
      break;
    default:
      throw new IllegalArgumentException("Mode value:" + tMode);
    }
  }
\$\endgroup\$
  • \$\begingroup\$ What is tMode? Please ensure that your code is posted with the proper context. \$\endgroup\$ – 200_success Apr 25 at 5:17
1
\$\begingroup\$

To answer your question exactly and with very little value: no. All those println's and traversal modes add unnecessary length to your code.

But lets get down to business... shortness is not always he most desirable feature of source code. Your choice of providing accessors for value but not for the left and right subtrees is questionable. Be consistent with how you expose and manipulate your fields.

You left out the context of dtfRecursion. Defining the traversal mode outside the traversal algorithm is odd. You could implment the traversal modes as separate classes. This would free you from the need to check the correctness of the tMode. Also you wouldn't need to worry about someone changing tMode during traversal (not that you do it now, eh).

It seems that you're just doing this for the sake of writing the algorithm but to make this review more useful, I'll point out that instead of hardcoding the println's you could pass a Consumer<Integer> to the traversal method and implement whatever you want to do with the values in that. And you could implement Node as a parameterized class to allow storage of types other than just integers.

Node is also a bit generic name for a class that is highly specific in it's implementation. BinaryTreeNode might be better.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.