我希望您能够进行尾递归遍历以下树形结构,而不必回到循环。
兄弟节点没有被正确遍历。如何解决这个问题?
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
兄弟节点没有被正确遍历。如何解决这个问题?
index
作为自由变量可能是一个可行的选项。那可能就是你所说的模拟堆栈。 - user6445533