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.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
思路
bfs遍历树,对任意一个节点,使用dfs,找到左侧与该节点相同的最长路径,在找到右侧与该节点相同的最长路径。使用dict记录值,减少寻找。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, parent):
if root == None:
return 0
if parent != root.val:
return 0
tmp = self.l.get(root)
tmp2 = self.r.get(root)
if tmp!=None and tmp2 != None:
return max(tmp, tmp2)
left = self.dfs(root.left, root.val)
right = self.dfs(root.right, root.val)
self.l[root] = left
self.r[root] = right
return 1+max(left, right)
def bfs(self, root):
que = []
que.insert(0, root)
ans = 0
while len(que) != 0:
cur = que.pop()
self.dfs(cur, cur.val)
ans = max(ans, self.l[cur]+self.r[cur])
if cur.left:
que.insert(0, cur.left)
if cur.right:
que.insert(0, cur.right)
return ans
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
self.l = {}
self.r = {}
return self.bfs(root)
代码虽然AC了, 但是运行时间很慢,进行优化下,使用一遍dfs即可。
判断如果结点不与父节点值一致就从当前开始。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, root, parent):
if root == None:
return 0
tmp = self.l.get(root)
tmp2 = self.r.get(root)
if tmp!=None and tmp2 != None:
return max(tmp, tmp2)
left = self.dfs(root.left, root.val)
right = self.dfs(root.right, root.val)
self.l[root] = left
self.r[root] = right
self.ans = max(self.ans, left+right)
if parent != root.val:
return 0
return 1+max(left, right)
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
self.l = {}
self.r = {}
self.ans = 0
self.dfs(root, root.val)
return self.ans