Teaching Kids Programming: Videos on Data Structures and Algorithms
Given the root of an n-ary tree, return the preorder traversal of its nodes’ values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]Input: root = [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]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Recursive Algorithm to Compute the Preorder Traversal Algorithm of a N-ary Tree
The preorder visits the root/current node, then recursively visit the children nodes from left to right. If there is only two children, then we are performing a preorder traversal on a binary tree (NLR).
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
ans = [root.val]
for x in root.children:
ans += self.preorder(x)
return ans
Preorder Traversal Algorithm of a N-ary Tree via Iteration
Alternatively, we can use a stack to emulate the Recursion. Pop from the stack, and then add the children in reverse order to the stack.
class Solution(object):
def preorder(self, root: 'Node') -> List[int]:
"""
:type root: Node
:rtype: List[int]
"""
if root is None:
return []
stack, output = [root], []
while stack:
root = stack.pop()
output.append(root.val)
stack.extend(root.children[::-1])
return output
Both algorithms have time complexity O(N) and space complexity O(N) where N is the number of the nodes in the given N-ary tree.
Also, using GoLang to perform a Recursive Depth First Search Algorithm to Traverse the N-nary Tree in Preorder: GoLang Programming: N-ary Tree Preorder Traversal Algorithm using Depth First Search
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: How to Retrieve the Camera Information (Meta Data) from JPEG Images using PHP?
Next Post: Teaching Kids Programming - Find Root of N-Ary Tree using Hash Set