0
0
DSA Goprogramming~30 mins

Height of Binary Tree in DSA Go - Build from Scratch

Choose your learning style9 modes available
Height of Binary Tree
📖 Scenario: You are working on a program that analyzes family trees. Each person is a node, and their children are connected below them. You want to find out how tall the family tree is, meaning the longest chain from the oldest ancestor down to the youngest descendant.
🎯 Goal: Build a program to create a simple binary tree, then calculate and print its height.
📋 What You'll Learn
Create a binary tree node struct called Node with value, left, and right fields
Create a sample binary tree with exactly 5 nodes using Node
Create a function called height that calculates the height of the binary tree
Print the height of the binary tree
💡 Why This Matters
🌍 Real World
Binary trees are used in many applications like organizing data, searching quickly, and representing hierarchical information such as family trees or file systems.
💼 Career
Understanding binary trees and recursion is essential for software developers working with data structures, algorithms, and system design.
Progress0 / 4 steps
1
Create the binary tree nodes
Create a struct called Node with an int field called value and two pointers to Node called left and right. Then create a binary tree with 5 nodes: root node with value 1, root's left child with value 2, root's right child with value 3, left child's left child with value 4, and left child's right child with value 5.
DSA Go
Hint

Define the struct first, then create the root node and assign its children.

2
Create the height function signature
Create a function called height that takes a pointer to Node named node and returns an int. This function will calculate the height of the binary tree.
DSA Go
Hint

Start the function by checking if the node is nil and return 0 in that case.

3
Implement the height calculation logic
Inside the height function, calculate the height of the left subtree by calling height(node.left) and store it in a variable called leftHeight. Similarly, calculate the height of the right subtree by calling height(node.right) and store it in rightHeight. Return the greater of leftHeight and rightHeight plus 1.
DSA Go
Hint

Use recursion to get heights of left and right subtrees, then return the bigger one plus one.

4
Print the height of the binary tree
In the main function, call height(root) and print the result using fmt.Println. Import the fmt package at the top.
DSA Go
Hint

Use fmt.Println(height(root)) to print the height.