Cody Reandeau Cody Reandeau - 1 year ago 77
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){

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

Prints the node values in the "inorder" order.
public void inOrder() {

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

System.out.print( + " ");

Main class:

public class Main {

public static void main(String[] args) {

BST tree = new BST();




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 Source

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.


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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download