Create a Binary Tree Manually in DSA Python - Time & Space Complexity
When we create a binary tree manually, we add nodes one by one. Understanding how long this takes helps us plan for bigger trees.
We want to know: how does the time to build the tree grow as we add more nodes?
Analyze the time complexity of the following code snippet.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
This code creates a binary tree by manually linking nodes to form a small tree.
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 here.
Each new node requires a fixed amount of work to create and link.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 node creations and links |
| 100 | 100 node creations and links |
| 1000 | 1000 node creations and links |
Pattern observation: The work grows directly with the number of nodes added.
Time Complexity: O(n)
This means the time to create the tree grows linearly with the number of nodes you add.
[X] Wrong: "Creating a tree manually is instant no matter how big it is."
[OK] Correct: Each node takes time to create and link, so bigger trees take more time.
Knowing how manual tree creation scales helps you understand more complex tree operations and their costs.
"What if we used a loop to create and link nodes instead of manual assignments? How would the time complexity change?"
Practice
data, left, and right?Solution
Step 1: Understand Node class constructor
The Node class constructor takes data as an argument and initializes left and right children as None.Step 2: Create root node with data
Usingroot = Node(10)creates a root node with data 10 and no children.Final Answer:
root = Node(10) # creates root with data 10 and no children -> Option AQuick Check:
Create root node with data = root = Node(10) [OK]
- Trying to create children directly without root
- Calling left or right as methods
- Creating node without data when constructor requires it
root?Solution
Step 1: Assign a new Node object to root.left
To add a left child, assign a new Node instance with data 5 toroot.left.Step 2: Check syntax correctness
root.left = Node(5)correctly creates and assigns the left child node.Final Answer:
root.left = Node(5) -> Option DQuick Check:
Assign left child node = root.left = Node(5) [OK]
- Calling left as a function instead of assigning
- Assigning data directly without creating Node
- Assigning integer directly to left attribute
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def print_tree(node):
if node is None:
return "null"
left_str = print_tree(node.left)
right_str = print_tree(node.right)
return f"{node.data} -> {left_str} -> {right_str}"
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
print(print_tree(root))Solution
Step 1: Trace print_tree calls recursively
Starting at root (1), print left subtree (2) then right subtree (3). Node 2 has left child 4 and no right child. Node 4 has no children.Step 2: Build output string step-by-step
Node 4 returns "4 -> null -> null". Node 2 returns "2 -> 4 -> null -> null -> null". Node 3 returns "3 -> null -> null". Root returns "1 -> 2 -> 4 -> null -> null -> null -> 3 -> null -> null".Final Answer:
1 -> 2 -> 4 -> null -> null -> null -> 3 -> null -> null -> Option BQuick Check:
Recursive print_tree output = 1 -> 2 -> 4 -> null -> null -> null -> 3 -> null -> null [OK]
- Missing null for empty children
- Confusing order of left and right
- Skipping nodes with no children
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = 3 # Error hereSolution
Step 1: Identify the error in assignment
Assigning3directly toroot.left.leftis wrong because it expects a Node object, not an integer.Step 2: Fix by creating a Node object for left child
Replaceroot.left.left = 3withroot.left.left = Node(3)to create a proper child node.Final Answer:
Assigning integer 3 directly to left child instead of Node object -> Option CQuick Check:
Child nodes must be Node objects, not raw values [OK]
- Assigning raw data instead of Node instance
- Confusing left and right child assignments
- Ignoring error messages about attribute access
10
/ \
5 15
\ \
7 20Which code snippet correctly creates this tree?
Solution
Step 1: Create root and immediate children
Root is 10, left child 5, right child 15.Step 2: Add right child 7 to left node and right child 20 to right node
Node 5 has right child 7, node 15 has right child 20.Step 3: Verify tree matches diagram
root = Node(10) root.left = Node(5) root.right = Node(15) root.left.right = Node(7) root.right.right = Node(20) matches the structure exactly with correct child assignments.Final Answer:
Code in Option A correctly creates the tree -> Option AQuick Check:
Assign children as per diagram: left.right=7, right.right=20 [OK]
- Assigning children to wrong side (left vs right)
- Swapping node data values
- Missing intermediate child nodes
Ready to prove it?
Pass the test and this pattern moves unknown
