简体   繁体   English

二叉树打印出所有的零

[英]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当我使用 inOrder 方法打印出这个二叉树的元素时,它打印: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!任何在正确方向上的帮助都会很棒,很抱歉我是个菜鸟!

In class Node your constructor is setting the constructor argument to itself instead of initializing the class variable.Node类中,您的构造函数将构造函数参数设置为自身,而不是初始化类变量。

Use the keyword this in your ctor to distinguish from constructor arguments and class variable.在构造函数中使用关键字this来区分构造函数参数和类变量。

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;
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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