题目描述
Category:Easy Tree
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
题目理解
给定一棵二叉树,查找每个节点具有相同值的最长路径的长度。两个节点之间的路径长度由他们之间的边数来表示。
解题思路
DFS
采用DFS的思想,求一个顶点到所有根节点的路径,时刻保留相等元素的最大值。相等元素的最大值是左右子树的相等元素的最大值+1。
定义的DFS函数是获得在通过root节点的情况下,最长单臂路径。其中更新的res是左右臂都算上的。所以这个题和普通的题是有点不一样。
思路学习:https://blog.csdn.net/fuxuemingzhu/article/details/79248926#DFS_53
class Solution:
# Runtime: 448ms 38.64% MemoryUsage: 16MB 100.00%
def longestUnivaluePath(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
self.getPath(root)
return self.res
def getPath(self, root):
if not root:
return 0
left = self.getPath(root.left)
right = self.getPath(root.right)
pl, pr = 0, 0
if root.left and root.left.val == root.val:
pl = 1 + left
if root.right and root.right.val == root.val:
pr = 1 + right
self.res = max(self.res, pl + pr)
return max(pl, pr)
用self.res记录过程中可能出现的连通路径(最大值路径),但往上一层返回的仅是左右子节点中的最大值,厉害哦!我就差了这一点!
MyMethod
有点问题的我的代码,失败testcase:[1,null,1,1,1,1,1,1]
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
if root is None:
return 0
if not root.left and not root.right:
return 0
left = self.longestUnivaluePath(root.left)
right = self.longestUnivaluePath(root.right)
if root.left and root.left.val == root.val:
left += 1
if root.right and root.right.val == root.val:
right += 1
if root.right and root.left and root.right.val == root.left.val and root.left.val == root.val:
return right + left
else:
return max(right, left)
Time
2020.3.23 测试用例教我成长!