📖 Scenario: Imagine you are building a system that manages a family tree. To keep the tree easy to search and update, you want to make sure it is balanced. A balanced tree means no branch is much longer than another, so finding family members is quick.
🎯 Goal: You will create a binary tree structure, add a helper variable, write a function to check if the tree is balanced, and finally print the result.
📋 What You'll Learn
Create a binary tree node struct called TreeNode with value, left, and right fields
Create a sample binary tree with exact values and structure
Add a helper function height to calculate the height of a subtree
Write a function is_balanced that returns true if the tree is balanced, false otherwise
Print the result of is_balanced for the sample tree
💡 Why This Matters
🌍 Real World
Balanced binary trees are used in databases and file systems to keep data organized for fast searching and updating.
💼 Career
Understanding tree balance is important for software engineers working with data structures, algorithms, and performance optimization.
Progress0 / 4 steps
1
Create the Binary Tree Node and Sample Tree
Create a struct called TreeNode with fields value: i32, left: Option>, and right: Option>. Then create a variable called root representing this tree:
1 / \
2 3 / 4
Use Some(Box::new(TreeNode { ... })) to build the tree exactly as shown.
DSA Rust
Hint
Use Option> for left and right children to allow empty branches.
2
Add a Helper Function to Calculate Height
Add a function called height that takes a reference to Option> and returns an i32. It should return 0 if the node is None. Otherwise, it returns 1 plus the maximum height of the left and right children.
DSA Rust
Hint
Use recursion to find the height of left and right children, then add 1 for the current node.
3
Write the Function to Check if Tree is Balanced
Write a function called is_balanced that takes a reference to Option> and returns a bool. It should return true if the tree is balanced, meaning the height difference between left and right children is at most 1 for every node. Use the height function to get heights and check balance recursively.
DSA Rust
Hint
Check the height difference at current node and recursively check left and right subtrees.
4
Print if the Tree is Balanced
Write a println! statement to print the result of is_balanced(&root). It should print true or false depending on the tree balance.
DSA Rust
Hint
Use println!("{}", is_balanced(&root)) to print the result.
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
Step 1: Understand balance condition
A balanced binary tree means for every node, the height difference between its left and right subtrees is at most 1.
Step 2: Eliminate incorrect options
All nodes having two children describes a full tree. Equal number of nodes in subtrees does not define balance. Sorted order defines a BST. None match the balance definition.
Final Answer:
The height difference between left and right subtrees of every node is at most 1 -> Option A
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 Rust function signature correctly represents a function that checks if a binary tree is balanced?
easy
A. fn is_balanced(root: Option) -> bool
B. fn is_balanced(root: Option<TreeNode>) -> bool
C. fn is_balanced(root: &Option) -> bool
D. fn is_balanced(root: TreeNode) -> bool
Solution
Step 1: Understand Rust ownership and references
Binary trees are usually represented with Option<Box<TreeNode>>. Passing by reference (&Option<Box<TreeNode>>) avoids moving ownership.
Step 2: Analyze the signatures
Passing Option<Box<TreeNode>> moves ownership. Option<TreeNode> is invalid due to infinite size. TreeNode directly ignores None roots. &Option<Box<TreeNode>> correctly borrows the tree.
Final Answer:
fn is_balanced(root: &Option<Box<TreeNode>>) -> bool -> Option C
Quick Check:
Use reference to Option<Box<TreeNode>> [OK]
Hint: Use &Option to avoid ownership moves [OK]
Common Mistakes:
Passing TreeNode directly instead of boxed option
Not using references causing ownership errors
Using Option<TreeNode> instead of Option
3. Given the following Rust code snippet, what will be the output?