2015-11-02 15 views
3

所以我想寫一個代碼,返回二叉搜索樹中的最小值。我知道這是樹的最左邊的價值,並且明白我需要它遞歸地運行到左邊,直到沒有剩下任何東西。但是我的代碼不工作,我不知道爲什麼。任何幫助,將不勝感激。BST-Smallest Scheme

(define (bst-smallest bs-tree) 
    (cond ((null? bs-tree) 
    (display "undefined")) 
    ((< (bst-value bs-tree) (bst-value (bst-left bs-tree))) 
    (bst-value (bst-left bs-tree))) 
    (else 
    (bst-smallest (bst-left bs-tree))) 
    )) 

回答

1

你只需要一直走到樹的左邊,直到你不能再走了。在你的代碼中,第二個條件是不正確的 - 沒有必要測試這些值,我們知道最左邊的元素將是最小的,構造。試試這個:

(define (bst-smallest bs-tree) 
    (cond ((null? bs-tree) 
     (display "undefined")) 
     ((null? (bst-left bs-tree)) 
     (bst-value bs-tree)) 
     (else 
     (bst-smallest (bst-left bs-tree))))) 
+1

謝謝!這更有意義! – Anon