【发布时间】:2019-05-13 18:23:28
【问题描述】:
基本上,我正在尝试实现这个算法,但也许有更好的方法来实现它。
- 从根开始
- 检查当前节点的每个子节点是否有带叶子的子节点(子节点)
- 如果当前节点的任何子节点有叶子,记录到当前节点(不是子节点)的路径并且不要继续沿着该路径继续下去。
- 否则继续 DFS
非功能性伪代码:
def find_paths(node):
for child in node.children:
if child.children.len() == 0
child_with_leaf = true
if child_with_leaf
record path to node
else
for child in node.children
find_paths(child)
例如:
:root
|- :a
| +- :x
| |- :y
| | +- :t
| | +- :l2
| +- :z
| +- :l3
+- :b
+- :c
|- :d
| +- :l4
+- :e
+- :l5
结果是:
[[:root :a]
[:root :b :c]]
这是我对 clojure 的破解:
(defn atleast-one?
[pred coll]
(not (nil? (some pred coll))))
; updated with erdos's answer
(defn children-have-leaves?
[loc]
(some->> loc
(iterate z/children)
(take-while z/branch?)
(atleast-one? (comp not empty? z/children))))
(defn find-paths
[tree]
(loop [loc (z/vector-zip tree)
ans nil]
(if (z/end? loc)
ans
(recur (z/next loc)
(cond->> ans
(children-have-leaves? loc)
(cons (->> loc z/down z/path (map z/node)))))))
)
(def test-data2
[:root [:a [:x [:y [:t [:l2]]] [:z [:l3]]]] [:b [:c [:d [:l4]] [:e [:l5]]]]]
)
更新:使用下面的 erdos 答案修复了崩溃,但我认为我的代码仍然存在问题,因为它会打印每条路径而不是所需的路径。
【问题讨论】:
标签: clojure