Create a Binary Tree Manually in DSA Rust - Time & Space Complexity
When we create a binary tree manually by linking nodes, we want to understand how the time to build it grows as we add more nodes.
We ask: How does the work increase when the tree gets bigger?
Analyze the time complexity of the following code snippet.
struct Node {
value: i32,
left: Option>,
right: Option>,
}
fn create_manual_tree() -> Node {
Node {
value: 1,
left: Some(Box::new(Node { value: 2, left: None, right: None })),
right: Some(Box::new(Node { value: 3, left: None, right: None })),
}
}
This code creates a simple binary tree with one root and two child nodes manually by linking nodes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating each node and linking it manually.
- How many times: Once per node; no loops or recursion here.
Each node is created one by one, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 node creations |
| 10 | 10 node creations |
| 100 | 100 node creations |
Pattern observation: The work increases linearly as we add more nodes.
Time Complexity: O(n)
This means the time to create the tree grows directly in proportion to the number of nodes.
[X] Wrong: "Creating a binary tree manually is constant time because we just write the code once."
[OK] Correct: Even though the code is written once, each node creation is a separate operation, so the total work grows with the number of nodes.
Understanding how manual tree creation scales helps you reason about building and traversing trees efficiently in real problems.
"What if we used a loop to create nodes instead of writing each one manually? How would the time complexity change?"
Practice
Solution
Step 1: Understand binary tree structure
A binary tree is a data structure where each node has at most two children, called left and right.Step 2: Purpose of manual creation in Rust
Manually creating a binary tree in Rust involves defining nodes and linking them with references to build this two-child structure.Final Answer:
To build a tree structure where each node can have up to two children -> Option CQuick Check:
Binary tree = nodes with up to two children [OK]
- Confusing binary tree with linked list
- Thinking binary tree nodes have more than two children
- Assuming binary tree stores data linearly
Solution
Step 1: Check for optional children
Binary tree nodes may or may not have children, so left and right should be Option types.Step 2: Use Box for heap allocation
Since nodes refer to other nodes recursively, Box is needed to allocate on heap and avoid infinite size.Final Answer:
struct Node { value: i32, left: Option, right: Option } -> Option AQuick Check:
Optional boxed children = correct node struct [OK]
- Using direct Node type causing infinite size error
- Not wrapping children in Option for nullable links
- Using references without lifetimes causing errors
println! statement?
struct Node {
value: i32,
left: Option,
right: Option,
}
fn main() {
let leaf = Node { value: 3, left: None, right: None };
let root = Node {
value: 1,
left: Some(Box::new(leaf)),
right: None,
};
println!("{}", root.left.as_ref().unwrap().value);
}Solution
Step 1: Understand tree structure
The root node has value 1, with left child node value 3 and no right child.Step 2: Trace the println! statement
root.left is Some(Box<Node>) containing leaf with value 3, so unwrap().value prints 3.Final Answer:
3 -> Option BQuick Check:
Access left child's value = 3 [OK]
- Printing root value instead of left child's
- Forgetting to unwrap Option before accessing value
- Confusing left and right children
struct Node {
value: i32,
left: Option,
right: Option,
}
fn main() {
let node = Node {
value: 5,
left: None,
right: None,
};
let root = Node {
value: 10,
left: Some(node),
right: None,
};
}Solution
Step 1: Identify the error cause
left field expects Option, but Some(node) tries to move Node directly, causing type mismatch.Step 2: Fix by boxing node
Wrap node in Box::new(node) inside Some to match Option type.Final Answer:
Error: cannot move `node` into `Some` because `node` does not implement Copy; fix by wrapping node in Box::new() -> Option AQuick Check:
Box node before Some to fix type error [OK]
- Trying to use node directly without Box
- Using references without lifetimes
- Ignoring compiler type mismatch errors
Solution
Step 1: Check node creation and boxing
Children must be boxed nodes wrapped in Some to match Option type.Step 2: Verify printing right child's value
Use root.right.as_ref().unwrap().value to safely access right child's value 15.Final Answer:
Code in option D correctly creates and prints right child's value 15 -> Option DQuick Check:
Box children and unwrap Option to print value [OK]
- Not boxing children nodes causing type errors
- Using unwrap() directly on Option without as_ref()
- Creating nodes without children or wrong types
Ready to prove it?
Pass the test and this pattern moves unknown
