[LeetCode] 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.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
这道题虽然是简单,但其实还是不简单。要求最长的路径,其实就是求根节点左右的最深路径相加,当然因为最长路径不一定经过根节点(如下图),所以这个根节点的值要和左右的最大值分别比较。
1
/ \
2 3
/ \
4 5
/ / \
6 7 8
\
9
\
10
有了这个基本的想法,那么解法一就是用分支的方法来求出根节点的周长,左边的最大周长,右边最大周长,然后取max,至于如何求最大周长,就要求该点的最大深度。但这个方法因为其实是用了两个recurive的方法来遍历了二叉树,所以时间复杂度是O(N2)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root: return 0
pass_root = self.get_max_height(root.left) + self.get_max_height(root.right)
return max(pass_root, self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right))
def get_max_height(self, root: TreeNode) -> int:
if not root:
return 0
left = self.get_max_height(root.left)
right = self.get_max_height(root.right)
return max(left, right) + 1
有了上面的思路,我们可以进一步优化。发现其实可以用一个全局变量来记录每个根节点的最大的周长。这样用一个求最深路径的recursive就行了,时间复杂度优化到O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.res = 0
self.get_max_height(root, self.res)
return self.res
def get_max_height(self, root: TreeNode, res: int) -> int:
if not root: return 0
left = self.get_max_height(root.left, self.res)
right = self.get_max_height(root.right, self.res)
self.res = max(self.res, left + right)
#print(self.res)
return max(left, right) + 1
posted on 2020-04-12 10:56 codingEskimo 阅读(108) 评论(0) 编辑 收藏 举报