Imagine exploring a magical tree network where each node has a special value! You're given a tree (a connected graph with no cycles) consisting of n nodes numbered from 0 to n-1, along with their values and connections.
Your mission is to find all the "good paths" in this tree. A good path is a journey between two nodes that follows these magical rules:
- ๐ฏ Same endpoints: The starting and ending nodes must have the same value
- ๐ Non-increasing journey: All nodes along the path must have values โค the endpoint values
For example, if you have a path A โ B โ C where A and C have value 3, then B must have value โค 3 for this to be a good path.
Note: Each single node counts as a good path by itself, and paths are undirected (AโB is the same as BโA).
Input & Output
Visualization
Time & Space Complexity
O(nยฒ) pairs to check times O(n) DFS for each pair
Space for recursion stack and grouping nodes by values
Constraints
- n == vals.length
- 1 โค n โค 3 ร 104
- 0 โค vals[i] โค 105
- edges.length == n - 1
- edges[i].length == 2
- 0 โค ai, bi < n
- The input represents a valid tree