1. 程式人生 > >JavaScript刷LeetCode -- 543. Diameter of Binary Tree

JavaScript刷LeetCode -- 543. Diameter of Binary Tree

一、題目

  Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

  Example:
  Given a binary tree 
           1
          / \
         2   3
        / \     
       4   5    
  Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

二、題目大意

  找出任意兩個節點最長路徑的長度。

三、解題思路

  這道題目實際上就是求一個節點的左右子樹高度之和的最大值。

四、程式碼實現

const diameterOfBinaryTree = root => {
  let sum = 0
  help(root)
  return sum
  function help (root) {
    if (!root) {
      return 0
    }
    const left = help(root.left)
    const right = help(root.right)
    sum = Math.max(sum, left + right)
    return Math.max(right, left) + 1
  }
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。