难以理解代码的递归部分

时间:2020-05-06 01:10:41

标签: javascript recursion binary-tree depth-first-search

我找到了解决此算法问题的方法:

给定一棵二叉树,您需要计算树直径的长度。二叉树的直径是一棵树中任何两个节点之间的最长路径的长度。此路径可能会也可能不会通过根。

示例: 给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

返回3,即路径[4,2,1,3]或[5,2,1,3]的长度。

注意:两个节点之间的路径长度由它们之间的边数表示。

代码:

class TreeNode {
    constructor(val, left, right) {
        this.val = (val === undefined ? 0 : val)
        this.left = (left === undefined ? null : left)
        this.right = (right === undefined ? null : right)
    }
}

const diameterOfBinaryTree = (root) => {
    let count = 0

    const dfs = (c) => {
        if (!c) return 0

        let left = dfs(c.left) // is this just going to the last node?
        let right = dfs(c.right) //what do left and right equal?
        count = Math.max(count, left + right) //since I don't know what left or right are 
                                              //it's hard to understand what I am comparing

        return 1 + Math.max(left, right) //why are we adding 1
    }
    dfs(root)
    return count
}


const tree = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3))

所以我的问题是: 左右分配给什么? 为什么我们要在返回值上加1?

我试图通过在代码中注释的每一行添加一个断点来逐步使用chrome开发器工具,但是对于发生的事情我仍然感到困惑。有没有一种方法可以控制台记录每次迭代的日志,以便我可以看到值的变化?当函数递归时,我无法在控制台日志记录值中取得成功,任何帮助都会很大。

0 个答案:

没有答案