Binary Tree Implementation in Golang

1. Introduction

A Binary Tree is a tree data structure in which each node has at most two children, typically referred to as the left and right child. It serves as the basis for several data structures and algorithms in computer science, including Binary Search Trees, Heaps, and balanced trees like AVLs.

2. Implementation Steps

1. Define a Node type with three fields: data (to store the actual value), left, and right (pointers to the left and right child nodes respectively).

2. Implement methods for inserting values (Insert), traversing in-order (InOrder), and displaying the tree (DisplayTree).

3. Implementation in Golang

package main
import (
	"fmt"
)
type Node struct {
	data  int
	left  *Node
	right *Node
}
func (n *Node) Insert(value int) {
	if value <= n.data {
		if n.left == nil {
			n.left = &Node{data: value}
		} else {
			n.left.Insert(value)
		}
	} else {
		if n.right == nil {
			n.right = &Node{data: value}
		} else {
			n.right.Insert(value)
		}
	}
}
func (n *Node) InOrder() {
	if n.left != nil {
		n.left.InOrder()
	}
	fmt.Print(n.data, " ")
	if n.right != nil {
		n.right.InOrder()
	}
}
func main() {
	root := &Node{data: 10}
	root.Insert(5)
	root.Insert(15)
	root.Insert(8)
	fmt.Print("InOrder Traversal: ")
	root.InOrder()
}

Output:

InOrder Traversal: 5 8 10 15

Explanation:

1. Node is the foundational element of the Binary Tree. It comprises of data, left, and right.

2. The Insert method is a recursive function. If the value to be inserted is less than or equal to the current node's data, it goes to the left child, otherwise, it goes to the right.

3. The InOrder method is an in-order traversal of the tree. It first visits the left child, then the current node, and finally the right child.

4. The main function demonstrates inserting nodes into the tree and displaying the in-order traversal of the tree.

This basic Binary Tree serves as a foundation. Further functionalities like deleting nodes, checking for the presence of a value, and balancing can be added based on specific requirements.


Comments