[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].

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

难度

Easy

方法

求出每个节点左右子树的深度,相加即为该节点对应的diameter,最后取最大的diameter即可

python代码

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def diameterOfBinaryTree(self, root):
        self.diameter = 0
        def depth(node):
            if node:
                l_depth = depth(node.left)
                r_depth = depth(node.right)
                self.diameter = max(self.diameter, l_depth + r_depth)
                return max(l_depth, r_depth) + 1
            return 0

        depth(root)
        return self.diameter


root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
assert Solution().diameterOfBinaryTree(root) == 3
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 天亮了, 梦也醒了。 这样的梦, 过去曾有, 现在不曾有。
    小剧在成长阅读 187评论 0 5
  • 有没有遇到过这样的一个人。 他很努力的向你走来,做尽一切博取欢心的事情。 给你很多的宠爱,以及纵容。 你觉得很感动...
    漠然然然阅读 441评论 3 3
  • 也不知道最近着了神马魔,喜欢大晚上不睡觉,是真的舍不得睡的那种,总有东西看不完,总有玩的没玩够……这样不好,真的!
    离生灭阅读 169评论 0 0
  • 往往一眨眼就偏离了正常的轨道。也许从开始就没有主线。为了一点鸡毛蒜皮的小事,浪费了许多时间。买了个kindle,却...
    cai_u阅读 132评论 0 1
  • 究竟要怎么做,才能热衷于某件事呢?才能打心底认定非此不可,并在这条路上勇往直前呢? —— 三浦紫苑《编舟记》 西冈...
    lambeta阅读 888评论 0 1