Bird
Raised Fist0
DSA Goprogramming~20 mins

Check if Binary Tree is Balanced in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
šŸŽ–ļø
Balanced Tree Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ā“ Predict Output
intermediate
2:00remaining
Output of Balance Check on Simple Tree
What is the output of the following Go code that checks if a binary tree is balanced?
DSA Go
package main
import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func isBalanced(root *TreeNode) bool {
    var check func(node *TreeNode) int
    check = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := check(node.Left)
        if left == -1 {
            return -1
        }
        right := check(node.Right)
        if right == -1 {
            return -1
        }
        if abs(left-right) > 1 {
            return -1
        }
        if left > right {
            return left + 1
        }
        return right + 1
    }
    return check(root) != -1
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}
    fmt.Println(isBalanced(root))
}
Afalse
Btrue
Cruntime error
Dcompilation error
Attempts:
2 left
šŸ’” Hint
Think about the height difference between left and right subtrees for each node.
ā“ Predict Output
intermediate
2:00remaining
Output of Balance Check on Unbalanced Tree
What is the output of the following Go code that checks if a binary tree is balanced?
DSA Go
package main
import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func isBalanced(root *TreeNode) bool {
    var check func(node *TreeNode) int
    check = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := check(node.Left)
        if left == -1 {
            return -1
        }
        right := check(node.Right)
        if right == -1 {
            return -1
        }
        if abs(left-right) > 1 {
            return -1
        }
        if left > right {
            return left + 1
        }
        return right + 1
    }
    return check(root) != -1
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Left.Left = &TreeNode{Val: 3}
    root.Left.Left.Left = &TreeNode{Val: 4}
    fmt.Println(isBalanced(root))
}
Acompilation error
Btrue
Cruntime error
Dfalse
Attempts:
2 left
šŸ’” Hint
Check the height difference at the root node.
🧠 Conceptual
advanced
2:00remaining
Understanding the Balance Check Algorithm
Which statement best describes how the balance check algorithm works in the given code?
AIt only checks leaf nodes to determine if the tree is balanced.
BIt traverses the tree in level order and counts nodes to decide balance.
CIt calculates the height of left and right subtrees and returns false immediately if difference is more than 1.
DIt uses a stack to store nodes and checks balance after traversal.
Attempts:
2 left
šŸ’” Hint
Think about how the function returns -1 to indicate imbalance.
šŸ”§ Debug
advanced
2:00remaining
Identify the Bug in Balance Check Code
What error will the following code produce when run?
DSA Go
package main
import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func isBalanced(root *TreeNode) bool {
    var check func(node *TreeNode) int
    check = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := check(node.Left)
        right := check(node.Right)
        if abs(left-right) > 1 {
            return -1
        }
        if left > right {
            return left + 1
        }
        return right + 1
    }
    return check(root) != -1
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Left.Left = &TreeNode{Val: 3}
    root.Left.Left.Left = &TreeNode{Val: 4}
    fmt.Println(isBalanced(root))
}
AIncorrect balance result due to missing imbalance check propagation
BNo error, outputs false
CStack overflow due to infinite recursion
DNo error, outputs true
Attempts:
2 left
šŸ’” Hint
Check if the function stops checking when imbalance is found in subtrees.
šŸš€ Application
expert
3:00remaining
Count Balanced Subtrees in a Binary Tree
Given a binary tree, which code snippet correctly counts how many subtrees are balanced?
DSA Go
package main
import "fmt"

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func countBalancedSubtrees(root *TreeNode) int {
    count := 0
    var check func(node *TreeNode) int
    check = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        left := check(node.Left)
        if left == -1 {
            return -1
        }
        right := check(node.Right)
        if right == -1 {
            return -1
        }
        if abs(left-right) > 1 {
            return -1
        }
        count++
        if left > right {
            return left + 1
        }
        return right + 1
    }
    check(root)
    return count
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Right = &TreeNode{Val: 5}
    fmt.Println(countBalancedSubtrees(root))
}
A5
B3
C4
D2
Attempts:
2 left
šŸ’” Hint
Count every subtree that returns a valid height (not -1).

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 a complete binary tree

Solution

  1. Step 1: Understand the balance condition

    A balanced binary tree means for every node, the height difference between its left and right subtree is at most 1.
  2. Step 2: Compare options with definition

    The height difference between left and right subtrees of every node is at most 1 matches the definition exactly. Other options describe different tree properties.
  3. Final Answer:

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

    Balanced tree = height difference ≤ 1 [OK]
Hint: Balance means height difference ≤ 1 at every node [OK]
Common Mistakes:
  • Confusing balanced with complete tree
  • Thinking balanced means equal number of nodes
  • Assuming all nodes must have two children
2. Which Go function signature correctly represents a function to check if a binary tree is balanced?
easy
A. func isBalanced(root *TreeNode) bool
B. func isBalanced(root TreeNode) int
C. func checkBalance(root *TreeNode) string
D. func balanced(root *TreeNode) void

Solution

  1. Step 1: Identify correct parameter and return types

    The function should take a pointer to the root node and return a boolean indicating balanced or not.
  2. Step 2: Match options with correct signature

    func isBalanced(root *TreeNode) bool matches: input is *TreeNode pointer, output is bool. Others have wrong return types or parameter types.
  3. Final Answer:

    func isBalanced(root *TreeNode) bool -> Option A
  4. Quick Check:

    Input pointer, output bool = correct signature [OK]
Hint: Check function returns bool and takes *TreeNode pointer [OK]
Common Mistakes:
  • Passing TreeNode by value instead of pointer
  • Returning int or string instead of bool
  • Using void (no return) for a check function
3. What will the output be for the following Go code snippet that checks if a binary tree is balanced?
package main
import "fmt"

type TreeNode struct {
    Val int
    Left, Right *TreeNode
}

func height(root *TreeNode) int {
    if root == nil {
        return 0
    }
    leftHeight := height(root.Left)
    rightHeight := height(root.Right)
    if leftHeight == -1 || rightHeight == -1 || abs(leftHeight-rightHeight) > 1 {
        return -1
    }
    if leftHeight > rightHeight {
        return leftHeight + 1
    }
    return rightHeight + 1
}

func isBalanced(root *TreeNode) bool {
    return height(root) != -1
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func main() {
    root := &TreeNode{Val: 1}
    root.Left = &TreeNode{Val: 2}
    root.Right = &TreeNode{Val: 3}
    root.Left.Left = &TreeNode{Val: 4}
    root.Left.Left.Left = &TreeNode{Val: 5}
    fmt.Println(isBalanced(root))
}
medium
A. Compilation error
B. true
C. false
D. Runtime panic

Solution

  1. Step 1: Analyze tree structure and height function

    The tree is left-heavy: left subtree has height 3, right subtree height 1 at root. Difference is 2 > 1, so height returns -1.
  2. Step 2: Check isBalanced return value

    isBalanced returns height(root) != -1, which is false here because height returned -1.
  3. Final Answer:

    false -> Option C
  4. Quick Check:

    Height difference > 1 means balanced = false [OK]
Hint: Height returns -1 if unbalanced; check != -1 for balanced [OK]
Common Mistakes:
  • Assuming tree is balanced without checking height difference
  • Confusing return values of height function
  • Ignoring left-heavy subtree depth
4. Identify the bug in this Go function that checks if a binary tree is balanced:
func isBalanced(root *TreeNode) bool {
    if root == nil {
        return false
    }
    leftHeight := height(root.Left)
    rightHeight := height(root.Right)
    if abs(leftHeight - rightHeight) > 1 {
        return false
    }
    return isBalanced(root.Left) && isBalanced(root.Right)
}
medium
A. Uses incorrect logical operator in return
B. Returns false for empty tree instead of true
C. Missing base case for leaf nodes
D. Does not check height difference correctly

Solution

  1. Step 1: Check base case for empty tree

    Function returns false if root is nil, but empty tree is balanced, so should return true.
  2. Step 2: Verify other logic correctness

    Height difference check and recursive calls are correct. Only base case return is wrong.
  3. Final Answer:

    Returns false for empty tree instead of true -> Option B
  4. Quick Check:

    Empty tree is balanced, so base case must return true [OK]
Hint: Empty tree is balanced; base case must return true [OK]
Common Mistakes:
  • Returning false for nil root
  • Not checking both subtrees recursively
  • Confusing logical AND with OR in recursion
5. Given a binary tree, how can you efficiently check if it is balanced without recalculating heights multiple times?
hard
A. Calculate height of left and right subtrees separately for each node
B. Check balance only at the root node
C. Use breadth-first traversal to count nodes at each level
D. Use a bottom-up recursion that returns height or -1 if unbalanced

Solution

  1. Step 1: Understand naive approach inefficiency

    Calculating height separately for each node causes repeated work, leading to O(n²) time.
  2. Step 2: Use bottom-up recursion for efficiency

    Return height if balanced, else -1 to stop early. This avoids repeated height calculations, achieving O(n) time.
  3. Final Answer:

    Use a bottom-up recursion that returns height or -1 if unbalanced -> Option D
  4. Quick Check:

    Bottom-up recursion avoids repeated height calls [OK]
Hint: Return -1 on unbalanced during height calc to stop early [OK]
Common Mistakes:
  • Recalculating heights multiple times causing slow code
  • Checking balance only at root misses subtree imbalance
  • Using BFS which doesn't help with height difference
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