LC 543. Diameter of Binary Tree

/**
 * 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
};
欢迎通过「邮件」或者点击「这里」告诉我你的想法
Welcome to tell me your thoughts via "email" or click "here"