我要遍历下面的树结构尾递归没有回落的环路:尾递归遍历树没有循环
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
兄弟姐妹没有正确穿过。如何才能做到这一点?
http://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure –
除非你想你不能只用tailrecursion遍历树手动维护一个堆栈。 – Bergi
你会如何用循环编写它?首先尝试一下,然后将该循环转换为尾递归函数。 – Bergi