mediumTreesPattern: BFS

Minimum Tree Traversal Path Solution

Problem Statement

Given a tree represented as an adjacency list, find the minimum path that visits all nodes exactly once.

Examples

Example 1:
Input:adjacencyList = [[], [2, 3], [3, 4], []], root = 1
Output:minimum path: 1 -> 2 -> 3 -> 4
Explanation: The minimum path that visits all nodes exactly once in the given tree is 1 -> 2 -> 3 -> 4.
Example 2:
Input:adjacencyList = [[], [2, 3], [3, 4, 5], [4]], root = 1
Output:minimum path: 1 -> 2 -> 3 -> 4 -> 5
Explanation: The minimum path that visits all nodes exactly once in the given tree is 1 -> 2 -> 3 -> 4 -> 5.
Example 3:
Input:adjacencyList = [[], [2, 3], [3, 4], [5, 6]], root = 1
Output:minimum path: 1 -> 2 -> 3 -> 4 -> 5 -> 6
Explanation: The minimum path that visits all nodes exactly once in the given tree is 1 -> 2 -> 3 -> 4 -> 5 -> 6.

Constraints

  • The tree is represented as an adjacency list.
  • Each node in the tree represents a unique value.
  • The tree is connected, meaning that all nodes are reachable from the root node.
  • Duplicate nodes can exist in the tree.
  • The tree can have multiple paths that visit all nodes exactly once.
Time: O(V + E) Space: O(V + E)
A more efficient approach is to use a Breadth-First Search (BFS) algorithm. Traverse the tree from the root node, keeping track of the nodes you have visited, and using a queue to store the nodes to be visited next.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.