给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
对任意节点而言,以其为根的直径长度是左子树高度 + 右子树高度。因此可以在计算节点的高度时,计算以其为根的直径长度。二叉树的直径长度就是所有节点的直径长度中的最大值。
# 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):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
max_path_count = [0]
def get_height(node):
if node is None:
return 0
left_height = get_height(node.left)
right_height = get_height(node.right)
height = 1 + max(left_height, right_height)
path_count = left_height + right_height
if path_count > max_path_count[0]:
max_path_count[0] = path_count
return height
get_height(root)
return max_path_count[0]