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:无法读取属性' 0'未定义的
我该怎么办?
答案 0 :(得分:0)
使用正确的数据结构,这意味着任何节点只有两个元素的长度,您将获得一个呼吸顺序排列的值列表(结果在这里是一个字符串)。
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));