LeetCode 687. Longest Univalue Path (dfs+bfs)
阿新 • • 發佈:2018-11-20
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