二叉树打印出全零

二叉树打印出全零

问题描述:

当我打印出来使用我的序法这种二叉树的元素,它打印:0 0 0 0 0 0二叉树打印出全零

这里是我的代码:

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

主要类:

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(); 

} 
} 

我有一种感觉,这是我的插入方法错了,我只是不知道什么。任何正确方向的帮助都会很棒,并且很抱歉成为新手!

在类Node您的构造函数将构造函数参数设置为自身,而不是初始化类变量。

在您的ctor中使用关键字this来区分构造函数参数和类变量。

例子:

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

} 
+0

谢谢!这工作! – Cody

+0

@CodyReandeau很高兴听到它:) – souldzin