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
childnode: simply connecttrailandcurand advance both - when there is a
childnode, then recursively call itself withbuild( trail = cur, cur = cur.child ). The call would connectcurnode with thelist in the next level. It would return the last node in next level. Then we assigntrail = last node in next levelandcur = cur.next in current level. This ensures that the next iteration would connectlast node in next leveltonext node in current level. - when
curbecomesnulltrailis the last node in current level.return trail
Code
| |
Complexity
Time complexity: $$O(n)$$
Space complexity: $$O(n)$$ {recursion stack}