graph
) to represent the adjacency list of the graph.graph
with the given adjacentPairs
, where each key is a node and the value is a list of its neighbors.root
) which has only one neighbor, indicating it is an end of the chain.ans
) with the root
.prev
(set to a value not in the graph) and curr
(set to root
), to traverse the graph.ans
is less than the number of unique elements:
a. For each neighbor of curr
, if the neighbor is not prev
, add it to ans
, update prev
to curr
, and curr
to the neighbor.
b. Break the inner loop to move to the next node.ans
.