Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

543. 二叉树的直径 #94

Open
webVueBlog opened this issue Sep 6, 2022 · 0 comments
Open

543. 二叉树的直径 #94

webVueBlog opened this issue Sep 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

543. 二叉树的直径

Description

Difficulty: 简单

Related Topics: , 深度优先搜索, 二叉树

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

示例 :
给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

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

**注意:**两结点之间的路径长度是以它们之间边的数目表示。

Solution

Language: JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
// dfs递归法
// 经过一个node,其左右子树的最大深度之和+1(二叉树的根节点深度为0)
// 定义一个递归函数depth(node)
// 计算node为起点的路径经过节点数res
// 函数返回该节点为根的子树的深度
var diameterOfBinaryTree = function (root) {
    let res = 0
    depth(root)
    return res

    function depth (node) {
        if (!node) return 0 // 节点不存在返回0
        let left = depth(node.left) // left为左子树的深度
        let right = depth(node.right) // right为右子树的深度
        res = Math.max(left + right, res) // 计算1+r 更新res
        return Math.max(left, right) + 1 // 返回该节点为根的子树的深度
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant