[LeetCode By Go 60]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].

Note: The length of path between two nodes is represented by the number of edges between them.

解題思路

遍歷二叉樹,求每個節點的左子樹深度和右子樹深度和的最大值。

代碼

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
var maxDiameter int
func MaxDeepth(t *TreeNode) (deepth int)  {
    if nil == t {
        return 0
    }

    left := MaxDeepth(t.Left)
    right := MaxDeepth(t.Right)

    maxDiameter = int(math.Max(float64(maxDiameter), float64(left + right)))

    return  int(math.Max(float64(left), float64(right))) + 1
}

func diameterOfBinaryTree(root *TreeNode) int {
    maxDiameter = 0
    if nil == root {
        return 0
    }

    MaxDeepth(root)

    return maxDiameter
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 經歷一些事,遇見一些人,每個人都會或多或少的改變。經歷一次便足夠。何苦還要為難自己,給他人再一起傷害你的機會...
    Miss微微恩閱讀 692評論 0 0
  • 文/任里昂 轉眼又要到情人節了,你是否還在為如何為男/女朋友挑選禮物而迷茫呢?本是吃吃吃、買買買、啪啪啪的好節日,...
    孫社長閱讀 754評論 2 6
  • 想我冷艷無雙,又想我待你如常 想我高貴無比,又想我輕佻隨意 想我溫柔美麗,又想我卑賤如蟻 想我孤絕傲岸,又想我融于...
    夕小桐閱讀 270評論 0 6
  • 有時別相信男人的鬼話!??說什么女人胖了安全點好,生活的真相會慢慢告訴你,還是努力做個瘦美人吧,窈窕淑女君子好...
    李玫閱讀 466評論 0 0