0
0
DSA Goprogramming~30 mins

Diameter of Binary Tree in DSA Go - Build from Scratch

Choose your learning style9 modes available
Diameter of Binary Tree
📖 Scenario: You are working on a network system where each node represents a server. The longest path between any two servers in the network is important for understanding the maximum communication delay. This longest path is called the diameter of the network tree.We will represent the network as a binary tree, where each node can have up to two child nodes (servers connected directly).
🎯 Goal: Build a Go program to calculate the diameter of a binary tree. The diameter is the number of nodes on the longest path between any two leaf nodes.
📋 What You'll Learn
Create a binary tree node struct called TreeNode with Val, Left, and Right fields
Create a sample binary tree with exactly 5 nodes with values 1, 2, 3, 4, 5 arranged as specified
Create a helper variable maxDiameter to track the maximum diameter found
Write a recursive function depth that returns the depth of a node and updates maxDiameter
Print the final diameter stored in maxDiameter
💡 Why This Matters
🌍 Real World
Network engineers use tree diameter to understand the longest communication delay in hierarchical networks.
💼 Career
Software developers and system architects often need to analyze tree structures for performance and optimization.
Progress0 / 4 steps
1
Create the binary tree structure and sample tree
Create a struct called TreeNode with fields Val int, Left *TreeNode, and Right *TreeNode. Then create a binary tree with root node value 1, left child 2, right child 3, left child of node 2 as 4, and right child of node 2 as 5. Store the root in a variable called root.
DSA Go
Hint

Define the struct first, then create nodes using &TreeNode{Val: value} and link them.

2
Add a variable to track the maximum diameter
Inside the main function, create an integer variable called maxDiameter and set it to 0. This will keep track of the longest path found so far.
DSA Go
Hint

Declare maxDiameter as an integer and initialize it to zero inside main.

3
Write the recursive depth function to update diameter
Write a recursive function called depth that takes a *TreeNode and returns an int. It should return 0 if the node is nil. Otherwise, it should recursively find the depth of left and right children, update maxDiameter with the sum of left and right depths if larger, and return the maximum depth plus 1. Call depth(root) inside main.
DSA Go
Hint

Use a recursive function that returns 0 for nil nodes, calculates left and right depths, updates maxDiameter, and returns max depth + 1.

4
Print the diameter of the binary tree
Add a fmt.Println statement inside main to print the value of maxDiameter.
DSA Go
Hint

Use fmt.Println(maxDiameter) to display the diameter.