【发布时间】:2014-06-16 08:40:00
【问题描述】:
我正在使用 gnu lisp 并希望获取到某个节点的路径。 我已经设法解决了二叉树的问题,但如果二叉树是 n 元,则找不到正确的递归规则。表示树(根 (subtree1) (subtree2) ...)。 那么,如何使用 GNU Lisp 获取 n 叉树中节点的路径?
二进制代码:
;checks if element e is in l
(defun partof(l e)
(cond
((null l) nil)
((equal l e) T)
((atom l) nil)
(T (find T (mapcar (lambda (l) (partof l e)) l)))))
;get the path
(defun path(l e)
(cond
((null l) nil)
((equal (car l) e) (list (car l))) ;if the element is the root of subtree return it
((partof (cadr l) e) (cons (car l) (path (cadr l) e))) ;if it is in the first subtree, get the root and check in first subtree until you get to it
((partof (caddr l) e) (cons (car l) (path(caddr l) e))) ; get the root and parse the second subtree
(T nil))) ;here i can't find the rule to check in the rest of the subtrees
我也对一种全新的方式感兴趣,而不仅仅是完成这个。 一棵n叉树是这样的: (root (subtree1) (subtree2) (subtree3) ...),例如 (A (B (C) (D)) (E (F) (G)) (H ( I) (J))) 是一棵完整的树。
A
/ | \
B E H
/\ /\ /\
C D F G I J
【问题讨论】:
-
"表示树(根 (subtree1) (subtree2) ...)。你能澄清一下树的结构吗?你想返回什么作为路径?
-
我举了一个树的例子。从根到节点的路径(传递给请求节点的所有节点)。通往 D 的路径:A、B、D。
-
您也可能对this post感兴趣。
-
@Mark,这篇文章是针对二叉树的。我为此编写了解决方案,我对 n-ary 树感兴趣。谢谢。
-
@CristiDeac Stack Overflow 是一个面向专业和狂热程序员的网站。大多数专业和狂热的程序员都会欣赏对类似问题的解决方案的参考,因为专业和狂热的程序员愿意考虑类似情况的解决方案,如何修改它们以适应新的问题情况。 Mark 并没有声称该帖子会解决您的问题,只是说它相似并且可能有用或有趣。 Stack Overflow 不是代码工厂。解决某些特定问题的高要求代码并不是获得有用结果的最佳方式