The idea is to keep 2 pointers. trail
pointer and cur
pointer. The
list is build in recursive function build(trail, cur)
which returns
last node of the list we build.
build
works as follows:
- when there is no
child
node: simply connecttrail
andcur
and advance both - when there is a
child
node, then recursively call itself withbuild( trail = cur, cur = cur.child )
. The call would connectcur
node with thelist in the next level
. It would return the last node in next level. Then we assigntrail = last node in next level
andcur = cur.next in current level
. This ensures that the next iteration would connectlast node in next level
tonext node in current level
. - when
cur
becomesnull
trail
is the last node in current level.return trail
Code
|
|
Complexity
Time complexity: $$O(n)$$
Space complexity: $$O(n)$$ {recursion stack}