[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微微恩阅读 3,994评论 0 0
  • 文/任里昂 转眼又要到情人节了,你是否还在为如何为男/女朋友挑选礼物而迷茫呢?本是吃吃吃、买买买、啪啪啪的好节日,...
    孙社长阅读 4,077评论 2 6
  • 想我冷艳无双,又想我待你如常 想我高贵无比,又想我轻佻随意 想我温柔美丽,又想我卑贱如蚁 想我孤绝傲岸,又想我融于...
    夕小桐阅读 1,833评论 0 6
  • 有时别相信男人的鬼话!👉说什么女人胖了安全点好,生活的真相会慢慢告诉你,还是努力做个瘦美人吧,窈窕淑女君子好...
    李玫阅读 3,255评论 0 0