LC 543. Diameter of Binary Tree

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * 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}
 */
var diameterOfBinaryTree = function (root) {
  if (root === null || (root.left === null && root.right === null)) return 0
  let res = 0
  function dfs(root) {
    if (root === null) return 0
    let left = dfs(root.left)
    let right = dfs(root.right)
    res = Math.max(res, left + right + 1)
    return Math.max(left, right) + 1
  }
  dfs(root)
  return res - 1
};





评论和交流请发送邮件到 me@tianhegao.com





通过以下渠道赞赏此文