2013-04-12 59 views
0

這是我在BST中使用兩種不同方式查找最小搜索關鍵字的實現,我想確保我是否正確地做到了這一點:查找二叉搜索樹中的最小元素(迭代和遞歸)

迭代

public T findSmallest (BinarySearchTree<T> tree) 

{ BinaryNode Node = new BinaryNode (tree.getDataRoot); 

    if (Node == null) return null; 

    while(Node.hasLeftChild()) Node = Node.getLeftChild; 

return Node.getData(); } 

遞歸

public T findSmallest (BinaryNode Node) 

{ if (Node == null) return null; 

    if(Node.getLeftChild()==null) return Node.getData(); 

    else 

    return findSmallest ((Node.getLeftChild()) ; } 
+0

一個測試? – thegrinner

+1

除了語法錯誤,命名約定和代碼格式,一切都應該沒問題 – jlordo

+2

你的單元測試說什麼?他們通過了嗎?請尊重Java命名約定。變量以小寫字母開頭。 –

回答

0

它看起來不錯,我重新格式化了一下代碼,希望我沒有錯過任何東西。

迭代

public T FindSmallest(BinarySearchTree<T> tree){ 
    BinaryNode Node = new BinaryNode(tree.getDataRoot()); 
    if (Node == null) 
    return null; 

    while(Node.hasLeftChild()) 
    Node = Node.getLeftChild(); 

    return Node.getData(); 
} 

遞歸

public T FindSmallest(BinaryNode Node){ 
    if (Node == null) 
    return null; 

    if(Node.getLeftChild()==null) 
    return Node.getData(); 

    return findSmallest(Node.getLeftChild()); 
} 

這您可能感興趣的:如果你想知道,如果你是對的,你爲什麼不跑Find kth smallest element in a binary search tree in Optimum way

+0

謝謝@TwoMore :) – GeekFlow

+0

@Sara:我希望這不是你的實際代碼,因爲(由於語法錯誤)它不會編譯。 – jlordo

+0

@TwoMore這兩種方法都不會按原樣編譯。在第一個,它有錯誤的返回類型,第二個也是,第二個在最後一行缺少一對括號... – jlordo