Cody Reandeau Cody Reandeau - 2 months ago 9
Java Question

Binary Tree printing out all zero's

When I print out the elements of this Binary Tree using my inOrder method, it prints: 0 0 0 0 0 0

Here is my Code:

public class BST {

class Node {

int data;
Node left;
Node right;

public Node(int data) {
data = data;
left = null;
right = null;
}

public Node root;

/**
* Method to insert a new node in order
* in our binary search tree
*/
public void insert(int data) {
root = insert(root, data);
}

public Node insert(Node node, int data){

if(node==null){
node = new Node(data);
}else if (data < node.data){
node.left = insert(node.left, data);
}else{
node.right = insert(node.right, data);
}
return node;
}

/**
Prints the node values in the "inorder" order.
*/
public void inOrder() {
inOrder(root);
}

private void inOrder(Node node) {
if (node == null)
return;

inOrder(node.left());
System.out.print(node.data + " ");
inOrder(node.right);
}
}


Main class:

public class Main {

public static void main(String[] args) {

BST tree = new BST();

tree.insert(6);
tree.insert(4);
tree.insert(8);
tree.insert(2);
tree.insert(1);
tree.insert(5);

tree.inOrder();

}
}


I have a feeling that it is something wrong in my insert method, I just can't figure out what. Any help in the right direction would be great, and sorry for being a noob!

Answer

In class Node your constructor is setting the constructor argument to itself instead of initializing the class variable.

Use the keyword this in your ctor to distinguish from constructor arguments and class variable.

Example:

public class Pair 
{

  private int left;
  private int right;

  public Pair(int left, int right) {
    // the following 2 lines don't do anything
    // it set's the argument "left = left" which is silly...

    left = left;
    right = right;

    // with the `this` keyword we can correctly initialize our class properties
    // and avoid name collision

    this.left = left;
    this.right = right;
  }

}