Tianhe Gao

LC 543. Diameter of Binary Tree

 1/**
 2 * Definition for a binary tree node.
 3 * function TreeNode(val, left, right) {
 4 *     this.val = (val===undefined ? 0 : val)
 5 *     this.left = (left===undefined ? null : left)
 6 *     this.right = (right===undefined ? null : right)
 7 * }
 8 */
 9/**
10 * @param {TreeNode} root
11 * @return {number}
12 */
13var diameterOfBinaryTree = function (root) {
14  if (root === null || (root.left === null && root.right === null)) return 0
15  let res = 0
16  function dfs(root) {
17    if (root === null) return 0
18    let left = dfs(root.left)
19    let right = dfs(root.right)
20    res = Math.max(res, left + right + 1)
21    return Math.max(left, right) + 1
22  }
23  dfs(root)
24  return res - 1
25};

No notes link to this note

Welcome to tell me your thoughts via "email"
UP