Leetcode 543. 二叉树的直径-----python

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
在这里插入图片描述
解题思路
注意看[4,2,1,3]或[5,2,1,3],是左右两棵子树路径加起来的。

  • 二叉树的直径:二叉树中从一个结点到另一个节点最长的路径,叫做二叉树的直径
  • 采用分治和递归的思想:根节点为root的二叉树的直径 =
    max(root-left的直径,root->right的直径,root->left的最大深度+root->right的最大深度+1)

python代码实现

class Solution(object):
    def __init__(self):
        self.res = 0

    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def getMaxDepth(root):
            if root == None:
                return 0
            left = getMaxDepth(root.left)
            right = getMaxDepth(root.right)
            self.res = max(self.res, left+right)
            return max(left, right) + 1

        if root == None: return 0
        getMaxDepth(root)
        return self.res

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/91492549