Bird
Raised Fist0
DSA Rustprogramming~20 mins

Height of Binary Tree in DSA Rust - 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 that calculates its height. What will be the printed height?

DSA Rust
struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

impl Node {
    fn height(&self) -> i32 {
        let left_height = match &self.left {
            Some(left_node) => left_node.height(),
            None => 0,
        };
        let right_height = match &self.right {
            Some(right_node) => right_node.height(),
            None => 0,
        };
        1 + std::cmp::max(left_height, right_height)
    }
}

fn main() {
    let tree = Node {
        value: 1,
        left: Some(Box::new(Node {
            value: 2,
            left: Some(Box::new(Node {
                value: 4,
                left: None,
                right: None,
            })),
            right: None,
        })),
        right: Some(Box::new(Node {
            value: 3,
            left: None,
            right: Some(Box::new(Node {
                value: 5,
                left: None,
                right: None,
            })),
        })),
    };
    println!("{}", tree.height());
}
A3
B2
C4
D5
Attempts:
2 left
💡 Hint

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

❓ Predict Output
intermediate
2:00remaining
What is the output of this height function on a single-node tree?

Given a binary tree with only one node, what will the height function print?

DSA Rust
struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

impl Node {
    fn height(&self) -> i32 {
        let left_height = match &self.left {
            Some(left_node) => left_node.height(),
            None => 0,
        };
        let right_height = match &self.right {
            Some(right_node) => right_node.height(),
            None => 0,
        };
        1 + std::cmp::max(left_height, right_height)
    }
}

fn main() {
    let tree = Node {
        value: 10,
        left: None,
        right: None,
    };
    println!("{}", tree.height());
}
A0
B2
C1
DNone
Attempts:
2 left
💡 Hint

Think about the height of a tree with only one node.

🔧 Debug
advanced
2:00remaining
Why does this height function cause a stack overflow?

Examine the following Rust code for height calculation. Why does it cause a stack overflow error?

DSA Rust
struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

impl Node {
    fn height(&self) -> i32 {
        let left_height = match &self.left {
            Some(left_node) => self.height(),
            None => 0,
        };
        let right_height = match &self.right {
            Some(right_node) => self.height(),
            None => 0,
        };
        1 + std::cmp::max(left_height, right_height)
    }
}
AThe function calls itself on self instead of left_node and right_node causing infinite recursion.
BThe function does not handle None cases properly causing panic.
CThe function uses Box<Node> incorrectly causing memory leak.
DThe function returns i32 instead of usize causing type mismatch.
Attempts:
2 left
💡 Hint

Look carefully at the recursive calls inside the match arms.

🧠 Conceptual
advanced
1:30remaining
What is the time complexity of the height calculation function?

Given a binary tree with n nodes, what is the time complexity of the recursive height function?

AO(1)
BO(log n)
CO(n^2)
DO(n)
Attempts:
2 left
💡 Hint

Consider how many nodes the function visits.

🚀 Application
expert
2:30remaining
What is the height of this unbalanced binary tree after insertions?

Consider inserting nodes in this order into an empty binary tree: 10, 5, 1, 7, 40, 50. What is the height of the resulting tree?

DSA Rust
struct Node {
    value: i32,
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

impl Node {
    fn insert(&mut self, val: i32) {
        if val < self.value {
            match &mut self.left {
                Some(left_node) => left_node.insert(val),
                None => self.left = Some(Box::new(Node { value: val, left: None, right: None })),
            }
        } else {
            match &mut self.right {
                Some(right_node) => right_node.insert(val),
                None => self.right = Some(Box::new(Node { value: val, left: None, right: None })),
            }
        }
    }

    fn height(&self) -> i32 {
        let left_height = match &self.left {
            Some(left_node) => left_node.height(),
            None => 0,
        };
        let right_height = match &self.right {
            Some(right_node) => right_node.height(),
            None => 0,
        };
        1 + std::cmp::max(left_height, right_height)
    }
}

fn main() {
    let mut root = Node { value: 10, left: None, right: None };
    root.insert(5);
    root.insert(1);
    root.insert(7);
    root.insert(40);
    root.insert(50);
    println!("{}", root.height());
}
A6
B3
C5
D4
Attempts:
2 left
💡 Hint

Draw the tree after all insertions and count the longest path.

Practice

(1/5)
1. What is the height of a binary tree with only one node (the root)?
easy
A. 1
B. Undefined
C. 2
D. 0

Solution

  1. Step 1: Understand height definition

    The height of a binary tree is the number of edges on the longest path from the root to a leaf.
  2. Step 2: Apply to single node tree

    With only one node (root), the longest path has length 0 edges.
  3. Final Answer:

    0 -> Option D
  4. Quick Check:

    Single node tree height = 0 [OK]
Hint: Height counts edges from root to deepest leaf [OK]
Common Mistakes:
  • Confusing height with number of nodes
  • Thinking empty tree has height 1
  • Assuming height starts at 1
2. Which of the following Rust function signatures correctly represents a function to calculate the height of a binary tree node defined as struct Node { left: Option, right: Option }?
easy
A. fn height(node: &Option) -> usize
B. fn height(node: Node) -> usize
C. fn height(node: &Node) -> usize
D. fn height(node: Option<Node>) -> usize

Solution

  1. Step 1: Analyze parameter types

    The tree nodes are wrapped in Option to allow nullability and heap allocation.
  2. Step 2: Choose correct reference type

    Passing a reference to Option (&Option) avoids moving ownership and allows checking for None.
  3. Final Answer:

    fn height(node: &Option) -> usize -> Option A
  4. Quick Check:

    Use &Option to handle nullable nodes safely [OK]
Hint: Use &Option to avoid ownership issues [OK]
Common Mistakes:
  • Passing Node by value moves ownership
  • Using Option<Node> instead of Option
  • Using &Node misses None case
3. Given the following Rust code, what is the printed height of the binary tree?
struct Node {
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
}

fn height(node: &Option<Box<Node>>) -> usize {
    match node {
        None => 0,
        Some(n) => 1 + height(n.left).max(height(n.right)),
    }
}

fn main() {
    let leaf = Node { left: None, right: None };
    let left_child = Node { left: Some(Box::new(leaf)), right: None };
    let root = Some(Box::new(Node { left: Some(Box::new(left_child)), right: None }));
    println!("{}", height(&root));
}
medium
A. 0
B. 2
C. 3
D. 1

Solution

  1. Step 1: Trace leaf node height

    The leaf node has no children, so height = 1 (0 + 1).
  2. Step 2: Trace left_child height

    Left_child has left = leaf (height 1), right = None (height 0), so height = 1 + max(1,0) = 2.
  3. Step 3: Trace root height

    Root has left = left_child (height 2), right = None (height 0), so height = 1 + max(2,0) = 3.
  4. Final Answer:

    3 -> Option C
  5. Quick Check:

    Height counts nodes on longest path = 3 [OK]
Hint: Count nodes from root to deepest leaf recursively [OK]
Common Mistakes:
  • Counting edges instead of nodes
  • Ignoring None children
  • Misreading recursive calls
4. Identify the bug in this Rust function to calculate binary tree height and select the correct fix:
fn height(node: Option<Box<Node>>) -> usize {
    if node.is_none() {
        return 0;
    }
    let n = node.unwrap();
    1 + height(n.left).max(height(n.right))
}
medium
A. Replace unwrap() with expect() to handle errors
B. Change parameter to &Option<Box<Node>> and use references to avoid moving ownership
C. Return 1 instead of 0 when node is None
D. Use Box<Node> instead of Option<Box<Node>> as parameter

Solution

  1. Step 1: Identify ownership issue

    Calling unwrap() moves ownership of node, making recursive calls invalid as ownership is lost.
  2. Step 2: Fix by using references

    Changing parameter to &Option<Box<Node>> allows borrowing without moving ownership, enabling safe recursion.
  3. Final Answer:

    Change parameter to &Option<Box<Node>> and use references to avoid moving ownership -> Option B
  4. Quick Check:

    Use references to prevent ownership errors in recursion [OK]
Hint: Use references to avoid moving nodes in recursion [OK]
Common Mistakes:
  • Using unwrap() moves ownership
  • Ignoring ownership rules
  • Changing return values incorrectly
5. You want to find the height of a binary tree but only have access to a vector of edges representing parent-child relationships as tuples (parent, child). Which approach correctly computes the height of the tree in Rust?
hard
A. Build the tree nodes from edges, then recursively compute height from root node
B. Count the number of edges in the vector and return that as height
C. Use the number of unique nodes as the height
D. Return the maximum child value from edges as height

Solution

  1. Step 1: Understand input format

    The vector of edges gives parent-child pairs but no direct tree structure.
  2. Step 2: Build tree structure

    Construct nodes and link children to parents to form the tree, identifying the root (node with no parent).
  3. Step 3: Compute height recursively

    Starting from root node, recursively calculate height by finding max height of left and right subtrees.
  4. Final Answer:

    Build the tree nodes from edges, then recursively compute height from root node -> Option A
  5. Quick Check:

    Build tree first, then compute height recursively [OK]
Hint: Convert edges to tree nodes before height calculation [OK]
Common Mistakes:
  • Using edge count as height
  • Ignoring tree structure
  • Assuming max child value equals height
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