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.

思路

  • 建一个全局变量count,存当前最大值,并且不受到recursive的影响
  • 在大方法里,传root,返回count
  • 用一个recursive方法求树的高度,如果nodeNone,返回0;每传进一个node, 先拿到左右两边的subtree分别的高leftrightcount = 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,136评论 0 10
  • 情景1客户之前看过但是并没看中的 答:这样的客户分两种情况1,之前没看中款式的,我们要给她推荐我们的新款,既然客户...
    廖雯同学阅读 3,959评论 0 0
  • 姓名:张义跃 245期谦虚1组学员 公司:本一设计 【日精进打卡第318天】 【知~学习】 《六项精进》诵读0遍共...
    小小蛋儿阅读 897评论 0 0
  • #17 1.发现了自己的不足 我觉得人最坚强的时候是敢于直面现实的时候。意识到自己的不足,意识到自己的长处,然后根...
    花花骚年阅读 3,118评论 0 0