Create a Binary Tree Manually in DSA Go - Time & Space Complexity
When we create a binary tree manually by linking nodes one by one, it is important to understand how the time needed grows as we add more nodes.
We want to know how the work increases when the tree gets bigger.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type Node struct {
value int
left *Node
right *Node
}
func main() {
root := &Node{value: 1}
root.left = &Node{value: 2}
root.right = &Node{value: 3}
root.left.left = &Node{value: 4}
root.left.right = &Node{value: 5}
fmt.Println(root)
}
This code creates a binary tree by manually assigning child nodes to each parent node.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and linking each node manually.
- How many times: Once per node added, no loops or recursion involved.
Each new node requires one operation to create and link it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly in proportion to the number of nodes added.
Time Complexity: O(n)
This means the time needed grows linearly with the number of nodes you add to the tree.
[X] Wrong: "Creating a binary tree manually is faster than any other method because there are no loops or recursion."
[OK] Correct: Even without loops, you still do one operation per node, so the total time grows with the number of nodes. No magic speedup happens.
Understanding how manual creation scales helps you reason about tree construction and compare it with automated or recursive methods.
"What if we used a loop to create and link nodes instead of manual assignments? How would the time complexity change?"