Hello!

Today we will consider the Depth-first Search algorithm. We have a tree and you need to go through all its elements from left to right. Take a tree for example

         1 - 6
           /    \
      2 - 4      10 - 6
         / \      \
    3 - 2  5 - 4 23 - 7

So there are 6 elements in this tree. We start from the root and go to the left branch to 4, this branch has two daughter branches, go to the left to 2, go back to 4 and go to the right to 5. Go back to the root and go to the right to 10 and the last element remains so let’s move on to it. As a result, we get 6, 4, 2, 5, 10, 23.

An example of an algorithm on golang

import "fmt"

type Node struct {
	Value    int
	Children []*Node
}

func main() {
	tree := Node{
		Value:    5,
		Children: []*Node{{Value: 3, Children: []*Node{{Value: 6}}}, {Value: 7, Children: []*Node{{Value: 8}}}},
	}
	fmt.Println(tree.DepthFirstSearch([]int{}))
}

func (n *Node) DepthFirstSearch(array []int) []int {
	array = append(array, n.Value)
	for _, child := range n.Children {
		array = child.DepthFirstSearch(array)
	}
	return array
}