[英]Tail Recursive Tree Traversal without Loops
我希望遞歸遍歷以下樹結構尾部而不回退循環 :
const o = {x:0,c:[{x:1,c:[{x:2,c:[{x:3},{x:4,c:[{x:5}]},{x:6}]},{x:7},{x:8}]},{x:9}]};
0
/ \
1 9
/ | \
2 7 8
/ | \
3 4 6
|
5
期望的結果: /0/1/2/3/4/5/6/7/8/9
我想需要一個閉包來啟用尾遞歸。 到目前為止我試過這個:
const traverse = o => {
const nextDepth = (o, index, acc) => {
const nextBreadth = () => o["c"] && o["c"][index + 1]
? nextDepth(o["c"][index + 1], index + 1, acc)
: acc;
acc = o["c"]
? nextDepth(o["c"][0], index, acc + "/" + o["x"]) // not in tail pos
: acc + "/" + o["x"];
return nextBreadth();
};
return nextDepth(o, 0, "");
};
traverse(o); // /0/1/2/3/4/5/7/9
兄弟姐妹沒有正確穿越。 如何才能做到這一點?
正如@Bergi所寫,如果您手動維護堆棧,解決方案很簡單。
const o = {x:0,c:[{x:1,c:[{x:2,c:[{x:3},{x:4,c:[{x:5}]},{x:6}]},{x:7},{x:8}]},{x:9}]} const traverse = g => { const dfs = (stack, head) => (head.c || []).concat(stack) const loop = (acc, stack) => { if (stack.length === 0) { return acc } const [head, ...tail] = stack return loop(`${acc}/${head.x}`, dfs(tail, head)) } return loop('', [g]) } console.log(traverse(o)) console.log(traverse(o) === '/0/1/2/3/4/5/6/7/8/9')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.