Bird
Raised Fist0
DSA Goprogramming~20 mins

Height of Binary Tree in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Tree Height Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the height of this binary tree?

Consider the following binary tree structure and code to calculate its height. What is the printed height?

DSA Go
package main

import "fmt"

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

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

func main() {
    root := &Node{Val: 1}
    root.Left = &Node{Val: 2}
    root.Right = &Node{Val: 3}
    root.Left.Left = &Node{Val: 4}
    root.Left.Right = &Node{Val: 5}
    fmt.Println(height(root))
}
A4
B2
C3
D5
Attempts:
2 left
💡 Hint

Height is the number of nodes on the longest path from root to a leaf.

❓ Predict Output
intermediate
2:00remaining
Output of height function on a skewed tree

What is the output of the height function for this skewed binary tree?

DSA Go
package main

import "fmt"

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

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

func main() {
    root := &Node{Val: 1}
    root.Right = &Node{Val: 2}
    root.Right.Right = &Node{Val: 3}
    root.Right.Right.Right = &Node{Val: 4}
    fmt.Println(height(root))
}
A0
B3
C1
D4
Attempts:
2 left
💡 Hint

Height counts nodes along the longest path from root to leaf.

🧠 Conceptual
advanced
1:00remaining
What does the height of an empty tree return?

In the height function for a binary tree, what is the returned height when the input root node is nil?

A0
B-1
C1
Dnil
Attempts:
2 left
💡 Hint

Think about the base case for recursion when there is no node.

🔧 Debug
advanced
2:30remaining
Why does this height function give wrong output?

Consider this height function code. It returns wrong height for some trees. What is the bug?

DSA Go
func height(root *Node) int {
    if root == nil {
        return -1
    }
    leftHeight := height(root.Left)
    rightHeight := height(root.Right)
    if leftHeight > rightHeight {
        return leftHeight
    }
    return rightHeight
}
AIt should return 0 for nil nodes instead of -1
BBoth B and C
CIt should add 1 to the max height of children before returning
DIt returns -1 for nil nodes and does not add 1 for current node height
Attempts:
2 left
💡 Hint

Check base case and how height is calculated from children.

🚀 Application
expert
3:00remaining
Calculate height of a binary tree with iterative approach

Which code snippet correctly calculates the height of a binary tree using an iterative method (level order traversal)?

A
func height(root *Node) int {
    if root == nil {
        return 0
    }
    queue := []*Node{root}
    height := 0
    for len(queue) > 0 {
        levelSize := len(queue)
        for i := 0; i < levelSize; i++ {
            node := queue[0]
            queue = queue[1:]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        height++
    }
    return height
}
B
func height(root *Node) int {
    if root == nil {
        return 0
    }
    stack := []*Node{root}
    height := 0
    for len(stack) > 0 {
        node := stack[len(stack)-1]
        stack = stack[:len(stack)-1]
        if node.Left != nil {
            stack = append(stack, node.Left)
        }
        if node.Right != nil {
            stack = append(stack, node.Right)
        }
        height++
    }
    return height
}
C
func height(root *Node) int {
    if root == nil {
        return 0
    }
    queue := []*Node{root}
    height := 1
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        if node.Left != nil {
            queue = append(queue, node.Left)
        }
        if node.Right != nil {
            queue = append(queue, node.Right)
        }
        height++
    }
    return height
}
D
func height(root *Node) int {
    if root == nil {
        return 0
    }
    var queue []*Node
    queue = append(queue, root)
    height := 0
    for len(queue) > 0 {
        levelSize := len(queue)
        for i := 0; i < levelSize; i++ {
            node := queue[0]
            queue = queue[1:]
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
        }
        height += 1
    }
    return height
}
Attempts:
2 left
💡 Hint

Height is number of levels. Use queue to process nodes level by level.

Practice

(1/5)
1. What does the height of a binary tree represent?
easy
A. The number of children of the root node
B. The total number of nodes in the tree
C. The number of leaf nodes in the tree
D. The number of edges on the longest path from root to a leaf

Solution

  1. Step 1: Understand the definition of height in a binary tree

    The height is the longest path from the root node down to the farthest leaf node, counted by edges.
  2. Step 2: Compare options with the definition

    Only The number of edges on the longest path from root to a leaf correctly describes the height as the number of edges on the longest root-to-leaf path.
  3. Final Answer:

    The number of edges on the longest path from root to a leaf -> Option D
  4. Quick Check:

    Height = longest root-to-leaf edges [OK]
Hint: Height counts edges, not nodes, from root to deepest leaf [OK]
Common Mistakes:
  • Confusing height with total nodes
  • Counting nodes instead of edges
  • Thinking height is number of leaves
2. Which Go function signature correctly defines a recursive function to find the height of a binary tree node?
easy
A. func height(root Node) string
B. func height(root *Node) int
C. func height(root *Node) bool
D. func height(root Node) float64

Solution

  1. Step 1: Identify correct parameter and return types for height function

    The function should accept a pointer to a Node and return an integer representing height.
  2. Step 2: Match options with correct signature

    func height(root *Node) int matches: func height(root *Node) int. Others have wrong parameter types or return types.
  3. Final Answer:

    func height(root *Node) int -> Option B
  4. Quick Check:

    Pointer input and int output for height [OK]
Hint: Height returns int; input is pointer to Node [OK]
Common Mistakes:
  • Using value instead of pointer for root
  • Returning wrong data type like bool or string
  • Incorrect function parameter types
3. What is the output of this Go code snippet that calculates the height of a binary tree?
package main

import "fmt"

type Node struct {
    left, right *Node
}

func height(root *Node) int {
    if root == nil {
        return 0
    }
    leftHeight := height(root.left)
    rightHeight := height(root.right)
    if leftHeight > rightHeight {
        return leftHeight + 1
    }
    return rightHeight + 1
}

func main() {
    root := &Node{
        left: &Node{},
        right: &Node{
            right: &Node{},
        },
    }
    fmt.Println(height(root))
}
medium
A. 3
B. 2
C. 4
D. 1

Solution

  1. Step 1: Analyze the tree structure

    The root has left child (leaf) and right child with its own right child (leaf). The longest path is root -> right -> right, which has 3 nodes and 2 edges.
  2. Step 2: Calculate height as edges + 1

    The function returns 1 + max height of children. The longest path has 2 edges, so height = 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Height counts edges + 1 for nodes [OK]
Hint: Count longest path edges + 1 for height [OK]
Common Mistakes:
  • Counting nodes instead of edges
  • Ignoring nil child nodes
  • Confusing left and right subtree heights
4. Identify the bug in this Go function that calculates the height of a binary tree:
func height(root *Node) int {
    if root == nil {
        return -1
    }
    leftHeight := height(root.left)
    rightHeight := height(root.right)
    if leftHeight > rightHeight {
        return leftHeight + 1
    }
    return rightHeight + 1
}
medium
A. Returning -1 for nil node causes incorrect height calculation
B. Missing base case for leaf nodes
C. Using pointers incorrectly for root
D. Not handling empty tree separately

Solution

  1. Step 1: Check base case return value

    The function returns -1 for nil nodes, which causes height to be off by one compared to standard definition.
  2. Step 2: Understand correct base case for height

    Height of empty tree should be 0 or 0 edges; returning -1 leads to negative heights and incorrect results.
  3. Final Answer:

    Returning -1 for nil node causes incorrect height calculation -> Option A
  4. Quick Check:

    Base case should return 0 for nil [OK]
Hint: Base case for nil must return 0, not -1 [OK]
Common Mistakes:
  • Returning -1 instead of 0 for nil
  • Confusing base case with leaf node
  • Not adding 1 after recursive calls
5. Given a binary tree where each node stores an integer, write a recursive Go function to find the height of the tree and also return the sum of all node values at the deepest level. Which approach correctly combines these tasks?
hard
A. Use iterative BFS to find height and sum nodes at last level in one pass
B. Calculate height first, then traverse tree again to sum deepest level nodes separately
C. Use a recursive function that returns both height and sum at deepest level by comparing left and right subtree results
D. Use recursion to sum all nodes and ignore height calculation

Solution

  1. Step 1: Understand combined task requirements

    We need height and sum of nodes at deepest level in one function efficiently.
  2. Step 2: Evaluate approaches

    Use a recursive function that returns both height and sum at deepest level by comparing left and right subtree results uses recursion returning height and sum together, avoiding multiple traversals.
  3. Step 3: Compare other options

    Calculate height first, then traverse tree again to sum deepest level nodes separately does two traversals, less efficient. Use iterative BFS to find height and sum nodes at last level in one pass is valid but iterative BFS is not recursive. Use recursion to sum all nodes and ignore height calculation ignores height, so incomplete.
  4. Final Answer:

    Use a recursive function that returns both height and sum at deepest level by comparing left and right subtree results -> Option C
  5. Quick Check:

    Combine height and sum in one recursive pass [OK]
Hint: Return height and sum together recursively to avoid extra traversal [OK]
Common Mistakes:
  • Doing two separate traversals
  • Ignoring sum at deepest level
  • Using iterative approach when recursion asked
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