首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎样压平一棵树?

怎样压平一棵树?
EN

Stack Overflow用户
提问于 2016-07-13 11:49:10
回答 1查看 91关注 0票数 1

我正在尝试定义一个topological-sort函数来产生一个图的拓扑排序的所有可能的顺序:

代码语言:javascript
复制
(define (topological-sort graph)
  (if (null? graph)
      `()
      (map (lambda (x)
             (cons x
                   (topological-sort (reduce x graph))))
           (no-in-edge graph))))

仅用于获取树(多层列表)

代码语言:javascript
复制
'((a
   (b
    (c
     (e
      (d (f))
      (f (d))))
    (e
     (c
      (d (f))
      (f (d)))
     (d
      (c
       (f)))))
   (e
    (b
     (c
      (d (f))
      (f (d)))
     (d
      (c (f))))
    (d
     (b
      (c
       (f)))))))

如何将树展开为列表列表?

代码语言:javascript
复制
a, b, c, e, f, d
a, e, b, c, f, d
a, b, e, c, f, d
a, e, d, b, c, f
a, e, b, d, c, f
a, b, e, d, c, f
a, b, c, e, d, f
a, e, b, c, d, f
a, b, e, c, d, f

我试过几个旅行功能,但都失败了。

总计划:

代码语言:javascript
复制
(define (no-in-edge graph)
  (filter (lambda (x)
            (and (element x
                               (vertex graph))
                 (not (element x
                                    (out-vertex graph)))))
          (vertex graph)))

(define (reduce x graph)
  (if (null? graph)
      `()
      (if (eq? x (caar graph))
          (reduce x
                  (cdr graph))
          (cons (car graph)
                (reduce x (cdr graph))))))

(define (element x list)
  (if (null? list)
      #f
      (if (eq? x (car list))
          #t
          (element x (cdr list)))))

(define (vertex graph)
  (map car graph))

(define (out-vertex graph)
  (remove-duplicates (apply append
                            (map cdr graph))))

(define (top-level graph)
  (apply append (topological-sort graph)))

(define (topological-sort graph)
  (if (null? graph)
      `()
      (map (lambda (x)
             (cons x
                   (topological-sort (reduce x graph))))
           (no-in-edge graph))))

(define test-graph `((a b c e)
                     (b c)
                     (c f)
                     (e d f)
                     (d)
                     (f)))

(topological-sort test-graph)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-13 16:37:03

如果使用(list-paths (car tree) '())调用,此过程将列出所有路径

代码语言:javascript
复制
(define list-paths
  (lambda (tree path)
    (if (null? (cdr tree))
        (reverse (cons (car tree) path))
        (map
         (lambda (subtree)
           (list-paths subtree (cons (car tree) path)))
          (cdr tree)))))

如果您想使结果扁平化,可以使用自定义过程(而不是通常的flatten,后者返回原子列表):

代码语言:javascript
复制
(define flatten
  (lambda (ll)
    (cond ((null? ll) ll)
          ((symbol? (car ll))
           (list ll))
          (else
           (append
            (flatten (car ll))
            (flatten (cdr ll)))))))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38342362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档