2016-10-01 266 views
1

當我打印出來使用我的序法這種二叉樹的元素,它打印: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(); 

} 
} 

我有一種感覺,這是我的插入方法錯了,我只是不知道什麼。任何正確方向的幫助都會很棒,並且很抱歉成爲新手!

回答

1

在類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