1743. Restore the Array From Adjacent Pairs

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1743

class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        def dfs(i, fa):
            res.append(i)
            for j in g[i]:
                if j != fa:
                    dfs(j, i)

        g = defaultdict(list)
        for a, b in adjacentPairs:
            g[a].append(b)
            g[b].append(a)
        i = next(i for i, v in g.items() if len(v) == 1)
        res = []
        dfs(i, 1e6)
        return res