2014-02-09 9 views
0

編寫需要一個整數n和包含整數n二叉搜索樹bst,並返回1和0的字符串計劃程序路徑的BST。向左移動對應於字符零('0'),右移對應於字符('1'),它接受一個整數n方案程序路徑和一個包含整數n

例如:

(path 17 '(14 (7() (12()())) 
(26 (20 (17()())())(31()())))) 
"100". 

在上面的例子中,我們得到的字符串100我們找到了路徑。我曾嘗試過,但我的路徑不正確。

+0

請將您所寫的代碼添加到問題中。否則,這聽起來像是你要求人們做你的功課;) –

回答

1

您沒有提供您迄今爲止編寫的代碼,因此我將草擬答案,以便您可以用自己的解決方案填充空白。假設n是樹:

(define (path n bst) 
    (cond ((< <???> n) ; if the current element is less than n 
     (string-append "1" <???>)) ; append 1, advance recursion to the right subtree 
     ((> <???> n) ; if the current element is greater than n 
     (string-append "0" <???>)) ; append 0, advance recursion to the left subtree 
     (else  ; we found n 
     <???>))) ; base case, end recursion with empty string 

關鍵是要遍歷樹,並積聚在同一時間的答案;鑑於輸出是一個字符串,我們使用string-append來構建它。

相關問題