Javascript 理解二叉树的递归部分有困难吗
我通过反复试验编写了这个函数,但我似乎无法理解递归部分是如何在两个路径中添加第一个元素的,或者在本例中是如何添加Javascript 理解二叉树的递归部分有困难吗,javascript,algorithm,recursion,binary-tree,nodes,Javascript,Algorithm,Recursion,Binary Tree,Nodes,我通过反复试验编写了这个函数,但我似乎无法理解递归部分是如何在两个路径中添加第一个元素的,或者在本例中是如何添加1->。代码如下: class TreeNode { constructor(val) { this.val = val; this.left = this.right = null; } } const binaryTreePaths = root => { if (!root) return null let
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))
对left和right节点的递归调用会将left和right子节点添加到我理解的路径中,但函数中的什么会添加第一个节点?这可能有助于重构函数:
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 + '->')
}
尝试使用调试器单步执行此操作,并记录
parentPath
和path
的值。递归调用会将节点.val
添加到用作递归调用参数的path
。它们不加左值和右值,而是在对左节点和右节点进行递归之前加上当前值(即1
)?;不幸的是,我仍然没有看到它发生在哪里。