[英]Recursive post order tree traversal without creating new nodes
我想定義一個適用於各種多路樹的通用尾遞歸樹遍歷。 這適用於預訂和水平順序,但我無法實現后訂單遍歷。 這是我正在使用的多向樹:
期望的訂單:EKFBCGHIJDA
只要我不關心尾遞歸,命令遍歷很容易:
const postOrder = ([x, xs]) => { xs.forEach(postOrder); console.log(`${x}`); }; const Node = (x, ...xs) => ([x, xs]); const tree = Node("a", Node("b", Node("e"), Node("f", Node("k"))), Node("c"), Node("d", Node("g"), Node("h"), Node("i"), Node("j"))); postOrder(tree);
另一方面,尾遞歸方法非常麻煩:
const postOrder = (p, q) => node => { const rec = ({[p]: x, [q]: forest}, stack) => { if (forest.length > 0) { const [node, ...forest_] = forest; stack.unshift(...forest_, Node(x)); return rec(node, stack); } else { console.log(x); if (stack.length > 0) { const node = stack.shift(); return rec(node, stack); } else return null; } }; return rec(node, []); }; const Node = (x, ...xs) => ([x, xs]); const tree = Node("a", Node("b", Node("e"), Node("f", Node("k"))), Node("c"), Node("d", Node("g"), Node("h"), Node("i"), Node("j"))); postOrder(0, 1) (tree);
特別是,我想避免創建新節點,以便我可以遍歷任意樹而無需了解其構造函數。 有沒有辦法做到這一點仍然保持尾遞歸?
堆棧安全
我的第一個答案是通過編寫我們自己的函數迭代器協議來解決這個問題。 不可否認,我渴望分享這種方法,因為這是我過去探索過的。 編寫自己的數據結構非常有趣,它可以為您的問題提供創造性的解決方案 - 如果我首先給出簡單的答案,您會感到無聊,不是嗎?
const Empty =
Symbol ()
const isEmpty = x =>
x === Empty
const postOrderFold = (f = (a, b) => a, acc = null, node = Empty) =>
{
const loop = (acc, [ node = Empty, ...nodes ], cont) =>
isEmpty (node)
? cont (acc)
: ???
return loop (acc, [ node ], identity)
}
const postOrderValues = (node = Empty) =>
postOrderFold ((acc, node) => [ ...acc, Node.value (node) ], [], node)
console.log (postOrderValues (tree))
// [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
以下為其他讀者提供完整解決方案......
const Node = (x, ...xs) => [ x, xs ] Node.value = ([ value, _ ]) => value Node.children = ([ _, children ]) => children const Empty = Symbol () const isEmpty = x => x === Empty const identity = x => x // tail recursive const postOrderFold = (f = (a, b) => a, acc = null, node = Empty) => { const loop = (acc, [ node = Empty, ...nodes ], cont) => isEmpty (node) ? cont (acc) : loop (acc, Node.children (node), nextAcc => loop (f (nextAcc, node), nodes, cont)) return loop (acc, [ node ], identity) } const postOrderValues = (node = Empty) => postOrderFold ((acc, node) => [ ...acc, Node.value (node) ], [], node) const tree = Node("a", Node("b", Node("e"), Node("f", Node("k"))), Node("c"), Node("d", Node("g"), Node("h"), Node("i"), Node("j"))) console.log (postOrderValues (tree)) // [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
相互遞歸
不知何故,這是你的問題,讓我畫出我最有靈感的作品。 回到樹遍歷的頂空中,我想出了這種偽應用和類型Now
and Later
。
Later
沒有正確的尾部呼叫,但我認為解決方案太整潔,不能分享它
const Empty =
Symbol ()
const isEmpty = x =>
x === Empty
const postOrderFold = (f = (a, b) => a, acc = null, node = Empty) =>
{
const Now = node =>
(acc, nodes) =>
loop (f (acc, node), nodes)
const Later = node =>
(acc, nodes) =>
loop (acc, [ ...Node.children (node) .map (Later), Now (node), ...nodes ])
const loop = (acc, [ reducer = Empty, ...rest ]) =>
isEmpty (reducer)
? acc
: reducer (acc, rest)
// return loop (acc, [ ...Node.children (node) .map (Later), Now (node) ])
// or more simply ...
return Later (node) (acc, [])
}
相互遞歸演示
const Node = (x, ...xs) => [ x, xs ] Node.value = ([ value, _ ]) => value Node.children = ([ _, children ]) => children const Empty = Symbol () const isEmpty = x => x === Empty const postOrderFold = (f = (a, b) => a, acc = null, node = Empty) => { const Now = node => (acc, nodes) => loop (f (acc, node), nodes) const Later = node => (acc, nodes) => loop (acc, [ ...Node.children (node) .map (Later), Now (node), ...nodes ]) const loop = (acc, [ reducer = Empty, ...rest ]) => isEmpty (reducer) ? acc : reducer (acc, rest) // return loop (acc, [ ...Node.children (node) .map (Later), Now (node) ]) // or more simply ... return Later (node) (acc, []) } const postOrderValues = (node = Empty) => postOrderFold ((acc, node) => [ ...acc, Node.value (node) ], [], node) const tree = Node("a", Node("b", Node("e"), Node("f", Node("k"))), Node("c"), Node("d", Node("g"), Node("h"), Node("i"), Node("j"))) console.log (postOrderValues (tree)) // [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
我們首先編寫Node.value
和Node.children
,它們從您的Node獲取兩個值
// -- Node -----------------------------------------------
const Node = (x, ...xs) =>
[ x, xs ]
Node.value = ([ value, _ ]) =>
value
Node.children = ([ _, children ]) =>
children
接下來,我們創建一個通用的Iterator
類型。 這個模仿本機可迭代行為,只有我們的迭代器是持久的(不可變的)
// -- Empty ----------------------------------------------
const Empty =
Symbol ()
const isEmpty = x =>
x === Empty
// -- Iterator -------------------------------------------
const Yield = (value = Empty, it = Iterator ()) =>
isEmpty (value)
? { done: true }
: { done: false, value, next: it.next }
const Iterator = (next = Yield) =>
({ next })
const Generator = function* (it = Iterator ())
{
while (it = it.next ())
if (it.done)
break
else
yield it.value
}
最后,我們可以實現PostorderIterator
const PostorderIterator = (node = Empty, backtrack = Iterator (), visit = false) =>
Iterator (() =>
visit
? Yield (node, backtrack)
: isEmpty (node)
? backtrack.next ()
: Node.children (node)
.reduceRight ( (it, node) => PostorderIterator (node, it)
, PostorderIterator (node, backtrack, true)
)
.next ())
我們可以看到它在這里與您的tree
一起工作
// -- Demo ---------------------------------------------
const tree =
Node ("a",
Node ("b",
Node ("e"),
Node ("f",
Node ("k"))),
Node ("c"),
Node ("d",
Node ("g"),
Node ("h"),
Node ("i"),
Node ("j")));
const postOrderValues =
Array.from (Generator (PostorderIterator (tree)), Node.value)
console.log (postOrderValues)
// [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
程序演示
// -- Node ---------------------------------------------- const Node = (x, ...xs) => [ x, xs ] Node.value = ([ value, _ ]) => value Node.children = ([ _, children ]) => children // -- Empty --------------------------------------------- const Empty = Symbol () const isEmpty = x => x === Empty // -- Iterator ------------------------------------------ const Yield = (value = Empty, it = Iterator ()) => isEmpty (value) ? { done: true } : { done: false, value, next: it.next } const Iterator = (next = Yield) => ({ next }) const Generator = function* (it = Iterator ()) { while (it = it.next ()) if (it.done) break else yield it.value } const PostorderIterator = (node = Empty, backtrack = Iterator (), visit = false) => Iterator (() => visit ? Yield (node, backtrack) : isEmpty (node) ? backtrack.next () : Node.children (node) .reduceRight ( (it, node) => PostorderIterator (node, it) , PostorderIterator (node, backtrack, true) ) .next ()) // -- Demo -------------------------------------------- const tree = Node ("a", Node ("b", Node ("e"), Node ("f", Node ("k"))), Node ("c"), Node ("d", Node ("g"), Node ("h"), Node ("i"), Node ("j"))); const postOrderValues = Array.from (Generator (PostorderIterator (tree)), Node.value) console.log (postOrderValues) // [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
與僅具有left
和right
字段的節點類型相比,可變參數children
字段使算法稍微復雜一些
這些迭代器的簡化實現使它們更容易比較。 在其他迭代器中為可變子項寫入支持留給讀者練習
// -- Node ---------------------------------------------
const Node = (value, left = Empty, right = Empty) =>
({ value, left, right })
// -- Iterators ----------------------------------------
const PreorderIterator = (node = Empty, backtrack = Iterator ()) =>
Iterator (() =>
isEmpty (node)
? backtrack.next ()
: Yield (node,
PreorderIterator (node.left,
PreorderIterator (node.right, backtrack))))
const InorderIterator = (node = Empty, backtrack = Iterator (), visit = false) =>
Iterator (() =>
visit
? Yield (node, backtrack)
: isEmpty (node)
? backtrack.next ()
: InorderIterator (node.left,
InorderIterator (node,
InorderIterator (node.right, backtrack), true)) .next ())
const PostorderIterator = (node = Empty, backtrack = Iterator (), visit = false) =>
Iterator (() =>
visit
? Yield (node, backtrack)
: isEmpty (node)
? backtrack.next ()
: PostorderIterator (node.left,
PostorderIterator (node.right,
PostorderIterator (node, backtrack, true))) .next ())
還有一個非常特殊的LevelorderIterator
,因為我認為你可以處理它
const LevelorderIterator = (node = Empty, queue = Queue ()) =>
Iterator (() =>
isEmpty (node)
? queue.isEmpty ()
? Yield ()
: queue.pop ((x, q) =>
LevelorderIterator (x, q) .next ())
: Yield (node,
LevelorderIterator (Empty,
queue.push (node.left) .push (node.right))))
// -- Queue ---------------------------------------------
const Queue = (front = Empty, back = Empty) => ({
isEmpty: () =>
isEmpty (front),
push: x =>
front
? Queue (front, Pair (x, back))
: Queue (Pair (x, front), back),
pop: k =>
front ? front.right ? k (front.left, Queue (front.right, back))
: k (front.left, Queue (List (back) .reverse () .pair, Empty))
: k (undefined, undefined)
})
// -- List ----------------------------------------------
const List = (pair = Empty) => ({
pair:
pair,
reverse: () =>
List (List (pair) .foldl ((acc, x) => Pair (x, acc), Empty)),
foldl: (f, acc) =>
{
while (pair)
(acc = f (acc, pair.left), pair = pair.right)
return acc
}
})
// -- Pair ----------------------------------------------
const Pair = (left, right) =>
({ left, right })
過度設計? 有罪。 除了JavaScript原語外,你可以換掉上面的接口。 在這里,我們交換懶惰的流,以獲得一系列渴望的值
const postOrderValues = (node = Empty, backtrack = () => [], visit = false) =>
() => visit
? [ node, ...backtrack () ]
: isEmpty (node)
? backtrack ()
: Node.children (node)
.reduceRight ( (bt, node) => postOrderValues (node, bt)
, postOrderValues (node, backtrack, true)
)
()
postOrderValues (tree) () .map (Node.value)
// [ 'e', 'k', 'f', 'b', 'c', 'g', 'h', 'i', 'j', 'd', 'a' ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.