Bird
Raised Fist0
DSA C#programming~30 mins

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

Choose your learning style10 modes available
Check if Binary Tree is Balanced
📖 Scenario: You are working on a program that manages a binary tree structure. To keep the tree efficient for searching, you need to check if the tree is balanced. A balanced binary tree means the height difference between left and right subtrees of every node is at most 1.
🎯 Goal: Build a C# program that creates a binary tree, sets a balance threshold, checks if the tree is balanced using a function, and prints the result.
📋 What You'll Learn
Create a binary tree with specific nodes
Add a variable to hold the balance threshold
Write a function to check if the tree is balanced
Print the result as 'Balanced' or 'Not Balanced'
💡 Why This Matters
🌍 Real World
Balanced binary trees are used in databases and search engines to keep data organized for fast searching and updating.
💼 Career
Understanding tree balance is important for software engineers working with data structures, algorithms, and performance optimization.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with an int val field, and TreeNode left and TreeNode right fields. Then create a binary tree with root node value 1, left child value 2, and right child value 3. Assign the left child of node 2 to a new node with value 4.
DSA C#
Hint

Define the TreeNode class first, then create the nodes and link them as described.

2
Set the Balance Threshold
Create an int variable called balanceThreshold and set it to 1.
DSA C#
Hint

Just create a simple integer variable named balanceThreshold and assign it the value 1.

3
Write the Function to Check if Tree is Balanced
Write a function called IsBalanced that takes a TreeNode root and returns a bool. Inside, define a helper function CheckHeight that returns the height of a node or -1 if unbalanced. Use balanceThreshold to check if the height difference between left and right subtrees is more than balanceThreshold. Return true if balanced, otherwise false.
DSA C#
Hint

Use a helper function inside IsBalanced to recursively check heights and return -1 if unbalanced.

4
Print if the Tree is Balanced
Use Console.WriteLine to print "Balanced" if IsBalanced(root) returns true, otherwise print "Not Balanced".
DSA C#
Hint

Use an if statement to check IsBalanced(root) and print the correct message.

Practice

(1/5)
1. What does it mean for a binary tree to be balanced?
easy
A. The height difference between left and right subtrees of every node is at most 1
B. All nodes have two children
C. The tree has the same number of nodes on left and right
D. The tree is sorted in ascending order

Solution

  1. Step 1: Understand balance condition

    A balanced binary tree means the height difference between left and right subtrees of every node is at most 1.
  2. Step 2: Compare other options

    Options B, C, and D describe different properties not related to balance.
  3. Final Answer:

    The height difference between left and right subtrees of every node is at most 1 -> Option A
  4. Quick Check:

    Balance means height difference ≤ 1 [OK]
Hint: Balance means subtree heights differ by no more than 1 [OK]
Common Mistakes:
  • Confusing balanced with complete or full tree
  • Thinking balance means equal number of nodes
  • Assuming sorted order means balanced
2. Which C# method signature correctly represents a function that checks if a binary tree is balanced?
easy
A. public bool IsBalanced(TreeNode root)
B. bool CheckBalance(int root)
C. public int IsBalanced(TreeNode root)
D. void IsBalanced(TreeNode root)

Solution

  1. Step 1: Identify correct return type and parameters

    The function should return a boolean indicating if the tree is balanced and take the root node as input.
  2. Step 2: Check method signature correctness

    public bool IsBalanced(TreeNode root) matches this: public bool IsBalanced(TreeNode root). Others have wrong return types or parameter types.
  3. Final Answer:

    public bool IsBalanced(TreeNode root) -> Option A
  4. Quick Check:

    Return bool, input TreeNode root [OK]
Hint: Check method returns bool and takes TreeNode root [OK]
Common Mistakes:
  • Using int return type instead of bool
  • Passing wrong parameter type like int
  • Using void return type for a check function
3. Given the following tree structure and code, what will be the output?
class TreeNode {
  public int val;
  public TreeNode left, right;
  public TreeNode(int v) { val = v; }
}

// Tree:
//     1
//    / \
//   2   3
//  /
// 4

TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);

bool result = IsBalanced(root);
Console.WriteLine(result);

bool IsBalanced(TreeNode node) {
  if (node == null) return true;
  int leftHeight = Height(node.left);
  int rightHeight = Height(node.right);
  if (Math.Abs(leftHeight - rightHeight) > 1) return false;
  return IsBalanced(node.left) && IsBalanced(node.right);
}

int Height(TreeNode node) {
  if (node == null) return 0;
  return 1 + Math.Max(Height(node.left), Height(node.right));
}
medium
A. Runtime exception
B. false
C. Compilation error
D. true

Solution

  1. Step 1: Calculate heights of subtrees

    Node 2 has left subtree height 1 (node 4) and right subtree height 0, difference is 1 (allowed). Node 1 has left height 2 and right height 1, difference is 1 (allowed).
  2. Step 2: Check balance recursively

    Node 4 and 3 are leaves (balanced). However, node 2's left subtree is height 1 and right is 0, difference 1 (balanced). So all nodes satisfy balance condition.
  3. Final Answer:

    true -> Option D
  4. Quick Check:

    Height difference ≤ 1 at all nodes = true [OK]
Hint: Check height difference at each node recursively [OK]
Common Mistakes:
  • Miscounting subtree heights
  • Not checking all nodes recursively
  • Assuming difference > 0 means unbalanced
4. The following code is intended to check if a binary tree is balanced. What is the bug?
bool IsBalanced(TreeNode node) {
  if (node == null) return true;
  int leftHeight = Height(node.left);
  int rightHeight = Height(node.right);
  if (Math.Abs(leftHeight - rightHeight) > 1) return false;
  return IsBalanced(node.left) || IsBalanced(node.right);
}

int Height(TreeNode node) {
  if (node == null) return 0;
  return 1 + Math.Max(Height(node.left), Height(node.right));
}
medium
A. Missing null check for node
B. Using || instead of && in recursive calls
C. Height function returns wrong value
D. Incorrect base case in IsBalanced

Solution

  1. Step 1: Analyze recursive condition

    The code uses || (OR) to combine left and right subtree balance checks, which returns true if either subtree is balanced.
  2. Step 2: Correct logic for balance check

    Both left and right subtrees must be balanced, so && (AND) should be used instead of ||.
  3. Final Answer:

    Using || instead of && in recursive calls -> Option B
  4. Quick Check:

    Balance requires both subtrees balanced, use && [OK]
Hint: Use && to combine subtree balance checks [OK]
Common Mistakes:
  • Using || instead of && in recursive checks
  • Ignoring base case for null nodes
  • Incorrect height calculation
5. You want to optimize the check for a balanced binary tree to avoid repeated height calculations. Which approach is best?
hard
A. Calculate height first, then check balance separately
B. Use BFS to check balance level by level
C. Calculate height and balance in one recursive function returning a tuple
D. Store heights in a global dictionary and update after each insertion

Solution

  1. Step 1: Understand repeated height calculation problem

    Calculating height separately for each node causes repeated work, increasing time complexity.
  2. Step 2: Use combined recursive approach

    Returning both height and balance status in one recursive call avoids repeated height calculations and improves efficiency.
  3. Final Answer:

    Calculate height and balance in one recursive function returning a tuple -> Option C
  4. Quick Check:

    Combine height and balance in one recursion for efficiency [OK]
Hint: Return height and balance together in one recursion [OK]
Common Mistakes:
  • Separating height and balance checks causing repeated work
  • Using BFS which doesn't directly check balance
  • Using global dictionary unnecessarily complicates code
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard