Bird
Raised Fist0
DSA C#programming

Check if Binary Tree is Balanced in DSA C#

Choose your learning style10 modes available
Mental Model
A balanced binary tree means no node has subtrees differing in height by more than one. We check heights bottom-up to confirm balance.
Analogy: Imagine a tree with branches. If one branch is much longer than its sibling, the tree is unbalanced and may topple. We measure branch lengths to ensure stability.
      1
     / \
    2   3
   / 
  4  
Dry Run Walkthrough
Input: Binary tree: 1 with left child 2, right child 3; 2 has left child 4
Goal: Determine if the tree is balanced by checking height differences at each node
Step 1: Check leaf node 4: height is 1, balanced
4 (height=1, balanced=true)
Why: Leaf nodes have height 1 and are balanced by definition
Step 2: Check node 2: left subtree height=1 (node 4), right subtree height=0 (null)
2 (left height=1, right height=0)
Why: Calculate heights of left and right subtrees to check balance
Step 3: Node 2 balance check: height difference is 1, balanced
2 (height=2, balanced=true)
Why: Height difference ≤ 1 means node 2 is balanced
Step 4: Check leaf node 3: height=1, balanced
3 (height=1, balanced=true)
Why: Leaf node 3 is balanced with height 1
Step 5: Check root node 1: left height=2 (node 2), right height=1 (node 3)
1 (left height=2, right height=1)
Why: Calculate heights of left and right subtrees for root
Step 6: Root node 1 balance check: height difference is 1, balanced
1 (height=3, balanced=true)
Why: Height difference ≤ 1 means root is balanced, so whole tree is balanced
Result:
Balanced tree confirmed: true
Annotated Code
DSA C#
using System;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    // Returns height if balanced, -1 if not balanced
    private int CheckHeight(TreeNode node) {
        if (node == null) return 0; // base case: empty subtree height 0

        int leftHeight = CheckHeight(node.left); // check left subtree height
        if (leftHeight == -1) return -1; // left subtree not balanced

        int rightHeight = CheckHeight(node.right); // check right subtree height
        if (rightHeight == -1) return -1; // right subtree not balanced

        if (Math.Abs(leftHeight - rightHeight) > 1) return -1; // current node unbalanced

        return Math.Max(leftHeight, rightHeight) + 1; // return height if balanced
    }

    public bool IsBalanced(TreeNode root) {
        return CheckHeight(root) != -1;
    }

    public static void Main() {
        TreeNode root = new TreeNode(1,
            new TreeNode(2,
                new TreeNode(4),
                null),
            new TreeNode(3));

        Solution sol = new Solution();
        Console.WriteLine(sol.IsBalanced(root));
    }
}
if (node == null) return 0;
base case: empty subtree has height 0
int leftHeight = CheckHeight(node.left);
recursively get left subtree height
if (leftHeight == -1) return -1;
if left subtree unbalanced, propagate failure
int rightHeight = CheckHeight(node.right);
recursively get right subtree height
if (rightHeight == -1) return -1;
if right subtree unbalanced, propagate failure
if (Math.Abs(leftHeight - rightHeight) > 1) return -1;
if height difference too big, mark unbalanced
return Math.Max(leftHeight, rightHeight) + 1;
return height of current subtree if balanced
return CheckHeight(root) != -1;
final check: tree balanced if no -1 returned
OutputSuccess
True
Complexity Analysis
Time: O(n) because we visit each node once to compute heights and check balance
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Naive approach checks balance at each node separately causing O(n^2) time; this bottom-up method is efficient O(n)
Edge Cases
Empty tree (root is null)
Returns true because empty tree is balanced
DSA C#
if (node == null) return 0;
Single node tree
Returns true because single node has balanced subtrees
DSA C#
if (node == null) return 0;
Unbalanced tree with one subtree much deeper
Returns false due to height difference > 1
DSA C#
if (Math.Abs(leftHeight - rightHeight) > 1) return -1;
When to Use This Pattern
When a problem asks if a binary tree is balanced, use a bottom-up height check with early stopping to efficiently detect imbalance.
Common Mistakes
Mistake: Checking balance top-down by computing subtree heights repeatedly causing O(n^2) time
Fix: Use bottom-up recursion that returns height and balance status together to achieve O(n) time
Mistake: Not handling null nodes as height 0 causing errors
Fix: Return 0 height for null nodes as base case
Summary
Checks if a binary tree is height-balanced by verifying height differences at every node.
Use when you need to confirm tree balance efficiently to avoid costly repeated height calculations.
The key insight is to combine height calculation and balance check in one bottom-up recursion with early stopping.

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