【问题标题】:Having trouble understanding the recursive portion of a binary tree DFS无法理解二叉树 DFS 的递归部分
【发布时间】:2020-08-04 17:35:51
【问题描述】:

我已经通过反复试验编写了这个函数,但我似乎无法理解递归部分是如何添加第一个元素的,或者在这种情况下是两个路径中的 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))

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

【问题讨论】:

  • 递归调用 donode.val 添加到用作递归调用参数的path。他们不添加左值和右值,而是在对左右节点进行递归之前添加 current 值(即1)。
  • 你能指出添加1的具体行吗?不幸的是,我仍然看不到它发生在哪里。

标签: javascript algorithm recursion binary-tree nodes


【解决方案1】:

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

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 的值。

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-09-30
    • 2016-04-19
    • 2014-03-29
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多