687. Longest Univalue Path

Medium

Problem:

Find the longest path with the same value.

https://leetcode.com/problems/longest-univalue-path/arrow-up-right

Solution:

You can solve this by descending to the leaf nodes of the tree using DFS and then backtracking while accumulating distance when the values match.

  1. For both left and right child nodes, check if they have the same value as the current node (i.e., the parent node). If so, increment the distance by 1 for each.

  2. The path will be the sum of the distances between the left and right child nodes.

  3. Lastly, pass the calculated distance up to the parent node. Since the parent node of the current node can't connect both left and right child nodes simultaneously, return the larger value between them as the status value. This is because, if you can only visit one place, it's better to visit the longer one.

Last updated