2013-05-16 77 views
1

我正在嘗試使用RACKET/DR編寫二叉樹的inorder遍歷算法。球拍二叉樹序列遍歷球拍

(define (print-records node number) 
     (cond 
     [(not (empty? node-left))(print-records (node-left node) number)] 
     *Do This before moving to next IF clause* 
     [(not (empty? node-right))(print-records(node-right node) number)] 

    )) 

我試圖按照下面的算法

InOrder(node) 
if node is null return 
InOrder(node.left) 
Print(node) 
InOrder(node.Right) 

我的問題是,通過COND我可以執行一個表達式,它會跳過休息。我嘗試在兩個表達式之一下添加兩個表達式,例如((a)(b))。我也嘗試做一個幫手程序,但是這也不起作用。

回答

2

您以錯誤的方式使用cond。請注意,您必須遞歸遍歷樹的左邊部分,然後訪問當前節點,然後遞歸遍歷樹的右邊部分 - 它們不是相互排斥的替代方案,需要按照該順序執行三個步驟。嘗試這樣的事情,而不是:

(define (print-records node number) 
    (unless (empty? (node-left node)) 
    (print-records (node-left node) number)) 
    (print (node-value node)) ; replace this line with the actual printing code 
    (unless (empty? (node-right node)) 
    (print-records (node-right node) number))) 

幾點說明:

  • (unless <condition> <body>)僅僅是(cond ((not <condition>) <body>))簡寫。
  • 遍歷的實際工作是在兩次遞歸調用之間完成的,在這種情況下,我以(print (node-value node))爲例,將該行替換爲當前節點值的實際打印代碼。
  • 目前尚不清楚您打算如何處理number參數,因爲它只是被傳遞,未被使用。
+0

它與* *打印功能的問題。它預計有一個表達式,但你提供了2個額外的(在我認爲的條件之後) – Achilles

+1

@Achilles正如我上面所說的那樣:這只是一個例子。我不知道你應該使用什麼打印功能,用實際代碼替換那一行。請重新閱讀我的答案,我編輯它以使其更清晰。 –

+0

在這一行中,我基本上想調用一個將輸出打印到用戶的函數(它在選擇要打印的內容之前對「數字」和節點值進行比較。) – Achilles

2

步行二叉樹是一個非常普遍的操作。您可以製作一個通用程序,然後使用該功能對其進行專門化,以應用於每個節點。

(define (walker node function) 
    (unless (empty? node) 
    (walker (node-left node) function) 
    (function node) 
    (walker (node-right node) function))) 

注:這是很好的函數的開始檢查empty?

(define (print-records node number) 
    (walker node (compose print node-value))) ; ignore number, it seems. 

你也可以將它作爲:

(define (walking-with function) 
    (letrec ((walker (lambda (node) 
        (unless (empty? node) 
         (walker (node-left node)) 
         (function node) 
         (walker (node-right node)))))) 
    walker)) 
(define print-records-for (walking-with (compose print node-value))) 
(print-records-for node) 
> ...