beepboop beepboop - 8 months ago 65
Java Question

Java member function for BST in order traversal

I recently was in a interview and was asked to code a in order traversal for a BST using the java member function prototype below.

public void inOrderPrint()

I was confused by the fact that it did not take in any parameters. I am used to the node to be passed in. It is very easy to traverse the tree with the node passed in... I am just a little confused how one would go about it without the initial reference?


The given signature makes sense if inOrderPrint() is defined in the Node class of the BST, then it's implied that the tree to traverse is the one rooted in the current node. Alternatively, it could be that the tree is an attribute in the current class. Assuming that the method is in the node class, it'd be something like this - and do notice how the recursion gets called:

public class Node {

  private Node left;
  private Node right;
  private Object value;

  public void inOrderPrint() {
    if (left != null)
    if (right != null)