問題描述
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.
Note: The length of path between two nodes is represented by the number of edges between them.
給定一個二叉樹,你需要計算樹的直徑的長度。二叉樹的直徑是樹中任意兩個節點之間最長路徑的長度。此路徑可以通過根目錄,也可以不通過根目錄。
注:兩個節點之間的路徑長度由節點之間的邊數表示。
給定一個二叉樹
1
/ \
2 3
/ \
4 5
返回 3, 爲路徑 [4,2,1,3] 或者 [5,2,1,3] 的長度.
Python 實現
# 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
"""
if root == None:
return 0
diameter = self.maxDepth(root.left) + self.maxDepth(root.right)
return max(diameter,
self.diameterOfBinaryTree(root.left),
self.diameterOfBinaryTree(root.right))
def maxDepth(self, node):
if node == None:
return 0
return 1 + max(self.maxDepth(node.left), self.maxDepth(node.right))