Discover how one smart check can save you hours of confusing tree balancing work!
Why Check if Binary Tree is Balanced in DSA C#?
Imagine you have a family tree drawn on paper. You want to quickly see if the tree is balanced, meaning no side is too heavy or too light compared to the other. Doing this by counting every branch and leaf manually is tiring and confusing.
Manually checking if a tree is balanced means counting the height of every branch and comparing them one by one. This is slow and easy to make mistakes, especially if the tree is big or changes often.
Using a smart method, we can check the balance of the tree while measuring its height in one go. This saves time and avoids errors by combining two tasks into one simple step.
int GetHeight(Node node) {
if (node == null) return 0;
int left = GetHeight(node.left);
int right = GetHeight(node.right);
if (Math.Abs(left - right) > 1) balanced = false;
return Math.Max(left, right) + 1;
}
// Call GetHeight(root) and check balanced flagbool IsBalanced(Node node, out int height) {
if (node == null) {
height = 0;
return true;
}
int leftHeight, rightHeight;
if (!IsBalanced(node.left, out leftHeight)) {
height = 0; return false;
}
if (!IsBalanced(node.right, out rightHeight)) {
height = 0; return false;
}
height = Math.Max(leftHeight, rightHeight) + 1;
return Math.Abs(leftHeight - rightHeight) <= 1;
}This lets you quickly and reliably check if a tree is balanced, which helps keep data organized and operations fast.
When building a search system, balanced trees keep searches fast. Checking balance ensures the system doesn't slow down as data grows.
Manual height checks are slow and error-prone.
Combined height and balance check is efficient and simple.
Balanced trees improve performance in many applications.
Practice
Solution
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.Step 2: Compare other options
Options B, C, and D describe different properties not related to balance.Final Answer:
The height difference between left and right subtrees of every node is at most 1 -> Option AQuick Check:
Balance means height difference ≤ 1 [OK]
- Confusing balanced with complete or full tree
- Thinking balance means equal number of nodes
- Assuming sorted order means balanced
Solution
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.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.Final Answer:
public bool IsBalanced(TreeNode root) -> Option AQuick Check:
Return bool, input TreeNode root [OK]
- Using int return type instead of bool
- Passing wrong parameter type like int
- Using void return type for a check function
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));
}Solution
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).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.Final Answer:
true -> Option DQuick Check:
Height difference ≤ 1 at all nodes = true [OK]
- Miscounting subtree heights
- Not checking all nodes recursively
- Assuming difference > 0 means unbalanced
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));
}Solution
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.Step 2: Correct logic for balance check
Both left and right subtrees must be balanced, so && (AND) should be used instead of ||.Final Answer:
Using || instead of && in recursive calls -> Option BQuick Check:
Balance requires both subtrees balanced, use && [OK]
- Using || instead of && in recursive checks
- Ignoring base case for null nodes
- Incorrect height calculation
Solution
Step 1: Understand repeated height calculation problem
Calculating height separately for each node causes repeated work, increasing time complexity.Step 2: Use combined recursive approach
Returning both height and balance status in one recursive call avoids repeated height calculations and improves efficiency.Final Answer:
Calculate height and balance in one recursive function returning a tuple -> Option CQuick Check:
Combine height and balance in one recursion for efficiency [OK]
- Separating height and balance checks causing repeated work
- Using BFS which doesn't directly check balance
- Using global dictionary unnecessarily complicates code
Ready to prove it?
Pass the test and this pattern moves unknown
