gpt4 book ai didi

JavaScript 与 python : Different output for a function with two recursion branches

转载 作者:行者123 更新时间:2023-11-30 23:56:28 25 4
gpt4 key购买 nike

我一直在将 python 代码翻译为 javascript,没有任何问题,但对于下面的示例,我未能这样做,并且不知道原因是什么。尽管代码相似,但 javascript 代码似乎产生了与 python 完全不同的输出。我已经调查了这个问题,看来 javascript 没有执行第二个递归分支?有人知道如何使 javascript 代码输出类似于 python 的输出吗?谢谢

1-Python代码:

def createNode(_id, right, left):
return {'id': _id, 'left': left, 'right': right}

n1 = createNode(1, None, None)
n2 = createNode(2, None, None)
n3 = createNode(3, None, None)
n4 = createNode(4, None, None)
n5 = createNode(1, n1, n2)
n6 = createNode(2, n3, n4)
n7 = createNode(3, n5, n6)

def DownTree(lst, node):
left = node['left']
right = node['right']

if(right == None):
lst.append(node['id'])
else:
DownTree(lst, right)
if(left == None):
lst.append(node['id'])
else:
print('will excute')
DownTree(lst, left)


lst = []
DownTree(lst, n7)

print(lst)
## outputs: [1, 1, 2, 2, 3, 3, 4, 4]

2- JavaScript 代码:

function createNode(_id, right, left){
return {'id': _id, 'left': left, 'right': right}
}
n1 = createNode(1, undefined, undefined)
n2 = createNode(2, undefined, undefined)
n3 = createNode(3, undefined, undefined)
n4 = createNode(4, undefined, undefined)
n5 = createNode(1, n1, n2)
n6 = createNode(2, n3, n4)
n7 = createNode(3, n5, n6)

function DownTree(lst, node){
left = node['left']
right = node['right']

if(right == undefined){
lst.push(node['id'])
}
else{
DownTree(lst, right)
}
if(left == undefined){
lst.push(node['id'])
}
else{
console.log('not executed!')
DownTree(lst, left)
}
}

lst = []
DownTree(lst, n7)
console.log(lst)
// outputs: [1, 1, 1, 3]

最佳答案

在您的 JS leftright 中,范围不正确。您需要将 varlet 添加到它们的定义中,以便它们不是全局的

var left = node['left']
var right = node['right']

关于JavaScript 与 python : Different output for a function with two recursion branches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61019082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com