简体   繁体   中英

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)
      left.inOrderPrint();
    System.out.println(value);
    if (right != null)
      right.inOrderPrint();
  }

}

Given that it's a member function,one can assume that you have access to the root (eg this.root). You could just overload this method with a method where you pass in a node. You would then call the overloaded method inside the given one with the root.

EDIT:

I thought the method was defined in the tree, not in the Node class. You could do it like this: (make sure to check for null!)

public void inOrderPrint(){
    //traverse down the left tree
    this.left.inOrderPrint();
    System.out.println(this); 
    //traverse down the right tree      
    this.right.inOrderPrint();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM