[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