2015-11-02 44 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