Leetcode 687. Longest Univalue Path (Python)
Related Topic
Depth-First-Search. Tree. Postorder-Traversal.
Description
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.
Sample I/O
Example 1
Input
5
/ \
4 5
/ \ \
1 1 5
Output: 2
Example 2
Input
1
/ \
4 5
/ \ \
4 4 5
Output: 2
Note
The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
Methodology
This question can be solved by Depth First Search.
Use DFS to traversal the tree in postorder. If the left child value or right child value is equal to root value. Then we add 1 to the number of root left edge or to the number root right edge. If the number of total edge (left edge + right egde) is greater than the max number of edges, then we update the max number of edges.
Code(DFS)
def longestUnivaluePath(self, root: TreeNode) -> int:
longest = [0]
def dfs(root):
if not root: return 0
left_len, right_len = dfs(root.left), dfs(root.right)
left=left_len + 1 if root.left and root.left.val == root.val else 0
right=right_len + 1 if root.right and root.right.val == root.val else 0
longest.append(max(longest.pop(), left+right))
return max(left, right)
dfs(root)
return longest[0]
BigO
We traversal all nodes of the tree once so time complexity is O(n)