GoLang Programming: N-ary Tree Preorder Traversal Algorithm using Depth First Search


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)

n-ary-tree-762x1024 GoLang Programming: N-ary Tree Preorder Traversal Algorithm using Depth First Search DFS Go Programming

n-ary-tree

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]

N-ary Tree Preorder Traversal Algorithm in GoLang

Using Depth First Search Algorithm, we can traverse the binary tree in pre-order. The DFS can be implemented using Recursion – see below GoLang implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */
 
func preorder(root *Node) []int {
    if root == nil {
        return []int{}
    }
    var ans = make([]int, 0)
    ans = append(ans, root.Val)    
    for i:=0; i < len(root.Children); i ++ {
        ans = append(ans, preorder(root.Children[i])...)
    }
    return ans
}
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func preorder(root *Node) []int {
    if root == nil {
        return []int{}
    }
    var ans = make([]int, 0)
    ans = append(ans, root.Val)    
    for i:=0; i < len(root.Children); i ++ {
        ans = append(ans, preorder(root.Children[i])...)
    }
    return ans
}

We use the triple dots … to append a list of ints to existing list of ints.

See also: GoLang Programming: N-ary Tree Preorder Traversal Algorithm using Depth First Search

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
302 words
Last Post: Teaching Kids Programming - Two Pointer Algorithm to Rescue People in Rocketship
Next Post: Teaching Kids Programming - Dynamic Programming Algorithm to Compute Minimum Number of Coins

The Permanent URL is: GoLang Programming: N-ary Tree Preorder Traversal Algorithm using Depth First Search

Leave a Reply