gpt4 book ai didi

javascript - 无法理解二叉树 DFS 的递归部分

转载 作者:行者123 更新时间:2023-12-02 21:01:08 25 4
gpt4 key购买 nike

我通过反复试验编写了这个函数,我似乎无法理解递归部分如何添加第一个元素,或者在本例中是两个路径中的 1-> 。这是代码:

class TreeNode {
constructor(val) {
this.val = val;
this.left = this.right = null;
}
}

const binaryTreePaths = root => {
if (!root) return null
let results = []
const dfs = (node, path) => {
if (!node.left && !node.right) return results.push(path + node.val)
if (node.left) dfs(node.left, path + node.val + '->')
if (node.right) dfs(node.right, path + node.val + '->')
}
dfs(root, '')
return results
}

const tree1 = new TreeNode(1)
tree1.left = new TreeNode(2)
tree1.right = new TreeNode(3)
tree1.left.right = new TreeNode(5)

console.log(binaryTreePaths(tree1))

对左右节点的递归调用将左子节点和右子节点添加到我理解的路径中,但是函数中的什么添加了第一个节点?

最佳答案

稍微重构一下函数可能会有所帮助:

const dfs = (node, parentPath) => {
const path = parentPath + node.val;
// ^^^^^^^^^^ magic happens here
if (!node.left && !node.right) return results.push(path)
if (node.left) dfs(node.left, path + '->')
if (node.right) dfs(node.right, path + '->')
}

尝试使用调试器单步调试此过程,并记录 parentPathpath 的值。

关于javascript - 无法理解二叉树 DFS 的递归部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61352577/

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