Compute the Diameter of a Binary Tree Using Go

 

 

This program calculates the diameter of a binary tree. The diameter of a tree is the number of nodes on the longest path between any two leaf nodes. This path may or may not pass through the root.

Program Explanation

The calculation involves a depth-first search (DFS) of the tree. Each recursive call returns the height of the current subtree while updating the maximum diameter found so far. The diameter at each node is the sum of the heights of its left and right subtrees.

Code Structure

  1. TreeNode struct: Defines the structure of the binary tree nodes.
  2. diameterOfBinaryTree function: Initializes and calls the recursive helper function.
  3. depth function: Recursive helper that calculates the depth and updates the diameter.

Code with Documentation

package main

import (
    "fmt"
)

// TreeNode defines a binary tree node.
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

// diameterOfBinaryTree computes the diameter of a binary tree.
func diameterOfBinaryTree(root *TreeNode) int {
    var diameter int
    depth(root, &diameter)
    return diameter
}

// depth computes the depth of the tree, updating the diameter as necessary.
// It returns the height of the tree rooted at the current node.
func depth(node *TreeNode, diameter *int) int {
    if node == nil {
        return 0
    }
    leftHeight := depth(node.Left, diameter)
    rightHeight := depth(node.Right, diameter)
    // Update diameter at this node
    *diameter = max(*diameter, leftHeight + rightHeight)
    // Return height of tree at this node
    return 1 + max(leftHeight, rightHeight)
}

// max returns the maximum of two integers.
func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

func main() {
    // Example binary tree
    root := &TreeNode{1, &TreeNode{2, &TreeNode{4, nil, nil}, &TreeNode{5, nil, nil}}, &TreeNode{3, nil, nil}}
    fmt.Println("The diameter of the binary tree is:", diameterOfBinaryTree(root))
}

Conclusion

The Go program efficiently computes the diameter of a binary tree by leveraging a depth-first search that calculates the maximum sum of the heights of the left and right subtrees at each node. This solution ensures optimal performance by avoiding repeated calculations of subtree heights.

 

Leave a Reply

Your email address will not be published. Required fields are marked *