题目要求:
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.
题目分析:
来求树的直径,也就是求可以不经过根节点的最大的长度。我们之前可以求出树的最大高度,此时来求树的左右深度然后对其进行微小的变形就可以得到经过根的最大的路径长度,然后从经过根节点和不经过根节点的左右子树中的最大路径长度来进行比较。
python代码:
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return max(self.longest_path(root.left)+self.longest_path(root.right), self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right))
def longest_path(self, root):
if root:
if root.left is None and root.right is None:
return 1
return 1 + max(self.longest_path(root.left), self.longest_path(root.right))
return 0
看一下大佬们的做法:大佬们省去了重复的计算,利用了类变量来作为全局变量来使用。
def diameterOfBinaryTree(self, root):
self.best = 1
def depth(root):
if not root: return 0
ansL = depth(root.left)
ansR = depth(root.right)
self.best = max(self.best, ansL + ansR + 1)
return 1 + max(ansL, ansR)
depth(root)
return self.best - 1
我一直觉得上面的那种算法,为什么要设计为减1的形式,可以直接全部减一,都不需要加1的操作,微做改进:
def diameterOfBinaryTree(self, root):
self.best = 0
def depth(root):
if not root: return 0
ansL = depth(root.left)
ansR = depth(root.right)
self.best = max(self.best, ansL + ansR)
return 1 + max(ansL, ansR)
depth(root)
return self.best
上述算法的关键,也是当前已有的记录最长路径与新的最长路径的最大值,所以,需要一个记录已有的最长路径的全局变量,也就是类变量来记录。
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
def depth(p):
if not p: return 0
left, right = depth(p.left), depth(p.right)
self.ans = max(self.ans, left+right)
return 1 + max(left, right)
depth(root)
return self.ans
好吧,上面的思路与我微调整的思路是一样的,说明大家的看法是一致的。