2015-10-03 17 views
1

這裏是印刷二叉搜索樹的中序遍歷的代碼: 公共類BSTPrint {爲什麼在我的BST的順序遍歷中顯示指針而不是字符串?

public void printInorder(BSTNode root){ 
    if (root!=null){ 
     printInorder(root.getLeftNode()); 
     System.out.println(root.getNodeValue()); 
     printInorder(root.getRightNode()); 
    } 

} 

public static void main(String[] argc){ 
    BSTPrint bstPrint = new BSTPrint(); 
    BSTNode<String> root=new BSTNode<String>(); 
    root.setNodeValue("5"); 
    BSTNode<String> rootLeft= new BSTNode<String>(); 
    rootLeft.setNodeValue("3"); 
    root.setLeftNode(rootLeft); 
    BSTNode<String> rootRight= new BSTNode<String>(); 
    rootRight.setNodeValue("8"); 
    root.setRightNode(rootRight); 
    bstPrint.printInorder(root); 
} 
} 

這裏的BSTNode類:

public class BSTNode<E> { 
    private E value; 
    private BSTNode<E> leftNode=null; 
    private BSTNode<E> rightNode=null; 

    public BSTNode getLeftNode(){ 
     return this.leftNode; 
    } 
    public void setLeftNode(BSTNode rootLeft){ 
     BSTNode newLeftNode=new BSTNode(); 
     newLeftNode.leftNode=null; 
     this.leftNode=newLeftNode; 
     newLeftNode.value=rootLeft; 
    } 
    public BSTNode getRightNode(){ 
     return this.rightNode; 
    } 
    public void setRightNode(BSTNode rootRight){ 
     BSTNode newRightNode=new BSTNode(); 
     newRightNode.rightNode=null; 
     this.rightNode=newRightNode; 
     newRightNode.value=rootRight; 
    } 

    public E getNodeValue(){ 
     return this.value; 
    } 

    public void setNodeValue(E value){ 
     this.value=value; 
    } 

} 

爲什麼我看到我的結果類似如下?

[email protected] 
5 
[email protected] 

代替

3 
5 
8 
+1

你的泛型全搞砸了。 – Rishav

+0

完全不相關,但這是您的代碼應該以適當的泛型來看待的方式。 http://ix.io/l9P – Rishav

回答

1

你setleft /右實際上是錯誤的:

他們應該是:

public void setRightNode(BSTNode rootRight){ 
    this.rightNode=rootRight; 
} 
public void setLeftNode(BSTNode rootLeft){ 
    this.leftNode=rootLeft; 
} 

你已經有一個節點 - 所以你只需要設置它。不需要創建額外的節點對象。提示:如果你看看你的IDE中的java警告,你會發現它抱怨你應該參數化你的一些值(總是在BSTNode的所有部分使用BSTNode)。一旦你添加它,它會告訴你它不能將BSTNode轉換成E,在你設置* Node函數中。

+0

感謝您的澄清。我現在對我來說非常合理:) –

1

在我的Java不新鮮,但我認爲你要定義BSTNode左右節點成員,像這樣:

public class BSTNode<E> { 
    private E value; 
    private BSTNode<E> leftNode=null; 
    private BSTNode<E> rightNode=null; 
} 
+0

我試過了,我仍然得到相同的結果 –

+0

您在'BSTNode '類中使用'BSTNode'而不是'BSTNode '。我懷疑它與此有關。按順序打印的邏輯對我來說似乎很好。 –

4

printInOrder工作就好了。左節點的值不是3;左節點的值是另一個節點,因爲setLeftNode

public void setLeftNode(BSTNode rootLeft){ 
    BSTNode newLeftNode=new BSTNode(); 
    newLeftNode.leftNode=null; 
    this.leftNode=newLeftNode; 
    newLeftNode.value=rootLeft; 
} 

不掛鉤提供rootLeft節點到this.leftNode。它創建另一個節點爲leftNode,並將該節點的設置爲rootLeft。同樣的問題出現在setRightNode。您需要修復setLeftNodesetRightNode。另外,如果您使用的是IDE(如Eclipse),那麼您知道IDE所顯示的所有位置都顯示黃色警告指示符?那些如果你把鼠標放在他們身上,它說你沒有正確使用泛型?如果您在IDE提醒您時包含了<E>,編譯器會爲您找到setLeftNodesetRightNode中的錯誤。

+0

Upvote for newching'newLeftNode.value = rootLeft'。 –

相關問題