LeetCode 543 二叉树的直径

543. 二叉树的直径

难度简单621收藏分享切换为英文接收动态反馈

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

示例 :
给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

任意节点当做最新的相对的根时,根到叶子即深度的路径是最远的,左子树深度+右子数的深度 max_path就得到最远路径;然后记录所有节点当做最新的相对根时,该max_path的最大值,最后返回它就是直径;用深度优先的后续遍历递归:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    max_path = 0
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.depth(root)
        return self.max_path

    def depth(self, root):
        if root is None:
            return 0

        left_depth = self.depth(root.left)
        right_depth = self.depth(root.right)

        new_path = left_depth + right_depth
        if self.max_path < new_path:
            self.max_path = new_path

        return max(left_depth, right_depth) + 1

猜你喜欢

转载自blog.csdn.net/Gordennizaicunzai/article/details/114230242