Golang program to perform inorder tree traversal


In Go programming language, a tree is a frequently used data structure that resembles an upside-down tree or an inverted tree with parent-child relationships between the nodes. In a tree, each node has a value and zero to many nodes as offspring. The root node is the node without a parent, while the leaves are the nodes without children. Trees can be employed for a variety of tasks, including data storage, sorting, and searching in hierarchical structures. We will use two methods to perform inorder tree traversal.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) and strings package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − To represent a binary tree node containing a value, a pointer to the left child node, and a pointer to the right child node, define a TreeNode struct.

  • Step 3 − Define an inorder_traversal function that accepts a pointer to the binary tree's root node and returns a slice of numbers showing the tree's inorder traversal.

  • Step 4 − If the root node is nil, the inorder_traversal function should return an empty slice.

  • Step 5 − Add the outcome of the inorder_traversal call made on the left child node to the output slice if the root node is not null.

  • Step 6 − The output slice should include the value of the current node.

  • Step 7 − Slice the output of the inorder_traversal call made on the right child node.

  • Step 8 − Return the output slice to the function.

  • Step 9 − Make a binary tree in the main function and call inorder_traversal on the root node.

  • Step 10 − The inorder traversal's outcome will be printed on the console using fmt.Println() function where ln means new line.

Example 1

In this example, we used recursion to execute the program.

package main
import "fmt"

// Definition for a binary tree node
type TreeNode struct {
   Val       int
   Left_val  *TreeNode
   Right_val *TreeNode
}

func inorder_traversal(root *TreeNode) []int {
   output := make([]int, 0)
   if root == nil {
      return output
   }
   output = append(output, inorder_traversal(root.Left_val)...)
   output = append(output, root.Val)
   output = append(output, inorder_traversal(root.Right_val)...)
   return output
}

func main() {
   root := &TreeNode{Val: 10}
   root.Left_val = &TreeNode{Val: 20}
   root.Right_val = &TreeNode{Val: 30}
   root.Left_val.Left_val = &TreeNode{Val: 40}
   root.Left_val.Right_val = &TreeNode{Val: 50}

   output := inorder_traversal(root)
   fmt.Println("The inorder traversal is given as:")
   fmt.Println(output) //print the inorder tree traversal
}

Output

The inorder traversal is given as:
[40 20 50 10 30]

Example 2

In this example, we will use stacks to implement the inorder tree traversal.

package main
import "fmt"

// Definition for a binary tree node
type TreeNode struct {
   Val  int
   Left_val  *TreeNode
   Right_val *TreeNode
}

func inorder_traversal(root *TreeNode) []int {
   result := make([]int, 0)
   stack := make([]*TreeNode, 0)
   curr := root

   for curr != nil || len(stack) > 0 {
      for curr != nil {
         stack = append(stack, curr)
         curr = curr.Left_val
      }
      curr = stack[len(stack)-1]
      stack = stack[:len(stack)-1]
      result = append(result, curr.Val)
      curr = curr.Right_val
   }
   return result
}

func main() {
   root := &TreeNode{Val: 10}
   root.Left_val = &TreeNode{Val: 20}
   root.Right_val = &TreeNode{Val: 30}
   root.Left_val.Left_val = &TreeNode{Val: 40}
   root.Left_val.Right_val = &TreeNode{Val: 50}

   result := inorder_traversal(root)
   fmt.Println("The inorder traversal can be represented as:")
   fmt.Println(result)  //print the inorder tree traversal
}

Output

The inorder traversal can be represented as:
[40 20 50 10 30]

Conclusion

We executed the program of inorder traversal using two methods. In the first example, we used recursion and in the second example we used stacks.

Updated on: 21-Feb-2023

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements