0
0
DSA Goprogramming~30 mins

Check if Binary Tree is Balanced in DSA Go - Build from Scratch

Choose your learning style9 modes available
Check if Binary Tree is Balanced
📖 Scenario: You are working on a system that manages hierarchical data like company departments or family trees. To keep the system efficient, you need to check if the binary tree structure is balanced. A balanced tree means the left and right subtrees of every node differ in height by no more than 1.
🎯 Goal: Build a Go program that creates a binary tree, sets up a helper function to check balance, implements the logic to check if the tree is balanced, and finally prints the result.
📋 What You'll Learn
Create a binary tree with the exact structure given
Add a helper function to calculate height and check balance
Implement the logic to check if the tree is balanced
Print true if balanced, false otherwise
💡 Why This Matters
🌍 Real World
Balanced binary trees are used in databases, file systems, and network routing to keep operations fast and efficient.
💼 Career
Understanding tree balance is important for software engineers working on performance-critical applications and data structure optimization.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Define a struct called Node with value as int, and pointers left and right to Node. Then create a variable root representing the root node with value 1, its left child with value 2, and right child with value 3. The left child of node 2 should have value 4, and the right child of node 2 should have value 5. The right child of node 3 should have value 6.
DSA Go
Hint

Start by defining the Node struct with the fields. Then create the root node and assign its children as pointers.

2
Add Helper Function to Check Height and Balance
Add a function called checkHeight that takes a pointer to Node and returns an int height and a bool indicating if the subtree is balanced. If the node is nil, return height 0 and balanced true. Recursively get left and right subtree heights and balance. If either subtree is unbalanced or the height difference is more than 1, return balanced false. Otherwise, return the height as max of left and right plus 1 and balanced true.
DSA Go
Hint

Use recursion to get height and balance status from left and right children. Compare heights and balance flags to decide current node's balance.

3
Implement Function to Check if Tree is Balanced
Add a function called isBalanced that takes a pointer to Node and returns a bool. It should call checkHeight on the node and return only the balance boolean.
DSA Go
Hint

Use the helper checkHeight function and return the balance boolean only.

4
Print if the Tree is Balanced
In the main function, add a line to print the result of calling isBalanced with root. It should print true if the tree is balanced, otherwise false.
DSA Go
Hint

Use fmt.Println to print the result of isBalanced(root).