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.

思路

  • 建一個(gè)全局變量count,存當(dāng)前最大值,并且不受到recursive的影響
  • 在大方法里,傳root,返回count
  • 用一個(gè)recursive方法求樹的高度,如果nodeNone,返回0;每傳進(jìn)一個(gè)node, 先拿到左右兩邊的subtree分別的高leftright,count = max(count, left + right);返回max(left, right)+1
class Solution:
    count = 0
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.getH(root)
        return self.count

    def getH(self, node):

        if not node:
            return 0
        left = self.getH(node.left)
        right = self.getH(node.right)
        self.count = max(self.count, left + right)     #update count
        return max(left, right)+1
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評論 0 10
  • 情景1客戶之前看過但是并沒看中的 答:這樣的客戶分兩種情況1,之前沒看中款式的,我們要給她推薦我們的新款,既然客戶...
    廖雯同學(xué)閱讀 821評論 0 0
  • 姓名:張義躍 245期謙虛1組學(xué)員 公司:本一設(shè)計(jì) 【日精進(jìn)打卡第318天】 【知~學(xué)習(xí)】 《六項(xiàng)精進(jìn)》誦讀0遍共...
    小小蛋兒閱讀 149評論 0 0
  • #17 1.發(fā)現(xiàn)了自己的不足 我覺得人最堅(jiān)強(qiáng)的時(shí)候是敢于直面現(xiàn)實(shí)的時(shí)候。意識到自己的不足,意識到自己的長處,然后根...
    花花騷年閱讀 483評論 0 0

友情鏈接更多精彩內(nèi)容