0

我真的很困惑如何做到这一点......我什至不知道如何开始,我知道如何为二叉树做这件事,但我希望能够用任何形式的嵌套列表来做,谁能帮帮我?

4

2 回答 2

2

对于这个,您需要使用模板来遍历任意嵌套的元素列表。例如,研究这个复制任意嵌套列表的过程:

(define (copy lst)
  (cond ((null? lst)                ; if list is empty
         '())                       ; return the empty list
        ((not (list? (car lst)))    ; if current element is not a list
         (cons (car lst)            ; cons current element
               (copy (cdr lst))))   ; with the rest of the list
        (else                       ; if current element is a list
         (cons (copy (car lst))     ; cons recursive call over current element
               (copy (cdr lst)))))) ; with recursive call over rest of the list

先来个小约定。假设这1是基本级别,并且所有返回的元素都将位于一个平面输出列表中(不保留输入列表的原始结构)。例如:

(elements-level '(1 2 3) 1)
; => '(1 2 3)

(elements-level '(1 (2) 3) 2)
; => '(2)

记住上面的模板,让我们看看如何修改它来解决手头的问题。我会让你填空,因为这个问题看起来像家庭作业:

(define (elements-level lst lvl)
  (cond ((or (null? lst) (< lvl 1))        ; if list is empty or below level
         '())                              ; return the empty list
        ((not (list? (car lst)))           ; if current element is not a list
         (if (= lvl <???>)                 ; if `lvl` is the base level
             (cons <???>                   ; cons current element in list
               (elements-level <???> lvl)) ; and advance recursion over cdr part
             (elements-level <???> lvl)))  ; else advance recursion over cdr part
        (else                              ; if current element is a list
         (append                           ; use `append` for flattening the list
          (elements-level <???> <???>)     ; recur over car, decrease one level
          (elements-level <???> <???>))))) ; recur over cdr, keep the same level

使用此列表测试过程,它必须返回'(1)level 1'(2)for level2等:

(elements-level '(1 (2 (3 (4 (5))))) 1)
; => '(1)
于 2012-11-11T20:27:13.660 回答
0

I think you can use recursion with steps as below:

  1. Define a list to hold all elements at nth depth.
  2. create a recursion function, which takes nested list, new list and n as argument
  3. For each element of the nested loop, call the recursion function itself by passing the child list and depth as n-1.
  4. Add all elements of the nested list to new list when n = 0.

Once this method is done, you will all elements of depth n in the new list.

Possible Enhancement: If it is possible the some of the list elements don't extend up to nth level, then you may want to check the type of elements before calling the recursion method. If it's of type leaf, then simply add the element in the new list.

于 2012-11-11T20:05:40.063 回答