如何将Python代码改写为Javascript?

2024-04-18 14:49:26 发布

您现在位置:Python中文网/ 问答频道 /正文

python中的代码是:

def trimTree(tree):
    p=tree[1]
    if type(p) == type(""): return p
    else :
        return(trimTree(p[0]),trimTree(p[1]))

树的位置:

[
  13,
  [ 6, [ 3, [Object], [Object] ], [ 3, 'a' ] ],
  [ 7, [ 3, 'b' ], [ 4, [Object], [Object] ] ]
]

转换时出现错误:

TypeError: Cannot read property '0' of undefined

我该怎么办?你知道吗


Tags: of代码treereadreturnifobjectdef
1条回答
网友
1楼 · 发布于 2024-04-18 14:49:26

使用适当的数据结构(这意味着任何节点只有两个元素的长度),可以得到一个按呼吸顺序排列的值列表(结果是一个字符串)。你知道吗

function trimTree(tree) { var p = tree[1]; return typeof p === 'string' ? p : trimTree(p[0]) + trimTree(p[1]); } var data = [ 13, [ [6, [ [3, [ [1, 'X'], [2, 'Y'] ] ], [3, 'a'] ] ], [7, [ [3, 'b'], [4, [ [2, 'Z'], [2, 'Q'] ] ] ] ] ] ]; console.log(trimTree(data));

相关问题 更多 >