Golang program to find the diameter of a tree


In this Golang article, we are going to find the diameter of a tree by using recursion and iterative method. The diameter of a tree is the number of nodes on the longest path between any two leaves in the tree.

Syntax

func diameter(root *node) int{…}

The diameter() function is used to find the diameter of a tree. It takes pointer to the root node as its argument.

Algorithm

  • Step 1 − First, we need to import the fmt package.

  • Step 2 − Now, create a struct of a single node of the tree named, node. It contains three fields, one is to hold integer data value of node while second and third points to the left and right node.

  • Step 3 − Define the function, new() to initialize a new node.

  • Step 4 − Now, create a diameter() function that takes a root node as input and returns the diameter of the tree rooted at that node.

  • Step 5 − The diameter of a tree is the number of nodes on the longest path between any two leaves in the tree.

  • Step 6 − Return 0, if the root node is nil.

  • Step 7 − Otherwise, calculate the height of the left and right subtrees using the height function and the diameters of the left and right subtrees recursively using the diameter function.

  • Step 8 − The diameter of the tree rooted at the current node is the maximum of the sum of the heights of the left and right subtrees plus one, and the diameters of the left and right subtrees.

  • Step 9 − Now, create a function named height() that takes a root node as input and returns the height of the tree rooted at that node.

  • Step 10 − Return 0, if the root node is nil. Otherwise, compute the heights of the left and right subtrees recursively and return the maximum of the two heights plus one.

  • Step 11 − Define max() function to return the maximum of two integers.

  • Step 12 − Start the main() function. Inside the main() function, call new() function to add nodes to the binary tree.

  • Step 13 − Now, call the diameter() function to find the diameter of the tree.

  • Step 14 − Further, the resultant diameter of the tree is printed on the screen by using the fmt.Println() function.

Example 1

In this example, we will define a diameter() function using recursive method that is used to find the diameter of a tree.

package main

import "fmt"

type node struct {
   left  *node
   right *node
   data  int
}

func new(data int) *node {
   return &node{nil, nil, data}
}

func diameter(root *node) int {
   if root == nil {
      return 0
   }
   leftH := height(root.left)
   rightH := height(root.right)

   leftD := diameter(root.left)
   rightD := diameter(root.right)

   return max(leftH+rightH+1, max(leftD, rightD))
}

func height(root *node) int {
   if root == nil {
      return 0
   }
   return 1 + max(height(root.left), height(root.right))
}

func max(a, b int) int {
   if a > b {
      return a
   }
   return b
}

func main() {
   root := new(4)
   root.left = new(3)
   root.right = new(2)
   root.left.left = new(1)
   root.left.right = new(5)

   fmt.Println("Diameter of the tree is: ", diameter(root))
}

Output

Diameter of the tree is:  4

Example 2

In this example, we will define a diameter() function using iterative method that is used to find the diameter of a tree.

package main

import (
   "fmt"
)

type TreeNode struct {
   val   int
   left, right *TreeNode
}

func diameter(root *TreeNode) int {
   if root == nil {
      return 0
   }

   stack := []*TreeNode{root}

   visited := make(map[*TreeNode]bool)

   maxDiameters := make(map[*TreeNode]int)

   maxDiameter := 0

   for len(stack) > 0 {
      node := stack[len(stack)-1]
      stack = stack[:len(stack)-1]

      visited[node] = true

      leftDiameter := 0
      rightDiameter := 0

      if node.left != nil {
         if _, ok := visited[node.left]; !ok {
            stack = append(stack, node.left)
         }
         leftDiameter = maxDiameters[node.left] + 1
      }

      if node.right != nil {
         if _, ok := visited[node.right]; !ok {
            stack = append(stack, node.right)
         }
         rightDiameter = maxDiameters[node.right] + 1
      }

      maxDiameter = max(maxDiameter, leftDiameter+rightDiameter)

      maxDiameters[node] = max(leftDiameter, rightDiameter)
   }

   return maxDiameter
}

func max(a, b int) int {
   if a > b {
      return a
   }
   return b
}

func main() {

   root := &TreeNode{val: 1}
   root.left = &TreeNode{val: 2}
   root.right = &TreeNode{val: 3}
   root.left.left = &TreeNode{val: 4}
   root.left.right = &TreeNode{val: 5}
   root.left.left.left = &TreeNode{val: 6}
   root.left.left.right = &TreeNode{val: 7}
   root.left.left.right.left = &TreeNode{val: 8}
   root.left.left.right.left.right = &TreeNode{val: 9}

   diameter := diameter(root)

   fmt.Printf("The diameter of the tree is: %d.\n", diameter)
}

Output

The diameter of the tree is:  2

Conclusion

We have successfully compiled and executed a go language program to we are going to find the diameter of a tree by using recursion and iterative methodalong with two examples. In the first example, we have used the recursive method and in the second example, we have used the iterative method.

Updated on: 10-May-2023

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements