N-ary Tree PreOrder Traversal 2

Title: N-ary Tree Preorder Traversal Source: leetcode.com

Given an n-ary tree, return the preorder traversal of its nodes’ values.

For example, given a 3-ary tree:

N-ary Tree

A 3-ary tree

Return its preorder traversal as: [1,3,5,6,2,4].

Note:

Recursive solution is trivial, could you do it iteratively?

You could find another explanation/ problem related to Preorder Traversal here.

Java solution (Recursive)

If you think closely about the recursive solution, what we are essentially doing is…
While parsing current node, we first add it’s value to the result list and then move on to each child turn by turn, in left to right order, parsing it as the next current node.

So, to get to an iterative solution, what we need to have is a stack where children to current node could be placed for parsing next and the catch is that they need to be put in reverse order so that the left most child becomes first candidate for parsing.

Python solution (Iterative)

Rate this post

2 thoughts on “N-ary Tree PreOrder Traversal

  1. Reply micky Jan 1,2020 7:12 am

    can you tell me why my solution fails for input

    [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

    it says that the output is [1,3,5,6,2,4,1,2,3,6,7,11,14,4,8,12,5,9,13,10]

    and expected is

    [1,2,3,6,7,11,14,4,8,12,5,9,13,10]

    when i saw the solution they are using extend functionality in python

    • Reply Anupam Jain Jun 28,2020 7:20 pm

      Hi Micky,

      Your solution fails because of the way you’re declared you res variable.

      This definition makes the res variable to be shared by all instances of Solution class (if you know Java it’s similar to static variables in it).
      So, in order to make your code work as expected all you need to do is make res a Data member/ instance variable.

      More specifically, define like this:

Leave a Reply