Height of Binary Tree in DSA Go - Time & Space Complexity
We want to understand how long it takes to find the height of a binary tree as the tree grows bigger.
How does the time needed change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
func height(root *Node) int {
if root == nil {
return 0
}
leftHeight := height(root.Left)
rightHeight := height(root.Right)
if leftHeight > rightHeight {
return leftHeight + 1
}
return rightHeight + 1
}
This code finds the height of a binary tree by checking the height of left and right subtrees recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Once per node in the tree.
As the number of nodes grows, the function visits each node once to calculate height.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls |
| 100 | About 100 calls |
| 1000 | About 1000 calls |
Pattern observation: The number of operations grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to find the height grows linearly with the number of nodes in the tree.
[X] Wrong: "The height calculation only depends on the longest path, so it should be O(log n)."
[OK] Correct: Even though height is about the longest path, the function must visit every node to be sure, so it takes time proportional to all nodes.
Understanding this helps you explain how recursive tree algorithms work and why visiting all nodes is often necessary.
"What if we stored the height at each node during insertion? How would the time complexity of finding height change?"
Practice
Solution
Step 1: Understand the definition of height in a binary tree
The height is the longest path from the root node down to the farthest leaf node, counted by edges.Step 2: Compare options with the definition
Only The number of edges on the longest path from root to a leaf correctly describes the height as the number of edges on the longest root-to-leaf path.Final Answer:
The number of edges on the longest path from root to a leaf -> Option DQuick Check:
Height = longest root-to-leaf edges [OK]
- Confusing height with total nodes
- Counting nodes instead of edges
- Thinking height is number of leaves
Solution
Step 1: Identify correct parameter and return types for height function
The function should accept a pointer to a Node and return an integer representing height.Step 2: Match options with correct signature
func height(root *Node) int matches: func height(root *Node) int. Others have wrong parameter types or return types.Final Answer:
func height(root *Node) int -> Option BQuick Check:
Pointer input and int output for height [OK]
- Using value instead of pointer for root
- Returning wrong data type like bool or string
- Incorrect function parameter types
package main
import "fmt"
type Node struct {
left, right *Node
}
func height(root *Node) int {
if root == nil {
return 0
}
leftHeight := height(root.left)
rightHeight := height(root.right)
if leftHeight > rightHeight {
return leftHeight + 1
}
return rightHeight + 1
}
func main() {
root := &Node{
left: &Node{},
right: &Node{
right: &Node{},
},
}
fmt.Println(height(root))
}Solution
Step 1: Analyze the tree structure
The root has left child (leaf) and right child with its own right child (leaf). The longest path is root -> right -> right, which has 3 nodes and 2 edges.Step 2: Calculate height as edges + 1
The function returns 1 + max height of children. The longest path has 2 edges, so height = 3.Final Answer:
3 -> Option AQuick Check:
Height counts edges + 1 for nodes [OK]
- Counting nodes instead of edges
- Ignoring nil child nodes
- Confusing left and right subtree heights
func height(root *Node) int {
if root == nil {
return -1
}
leftHeight := height(root.left)
rightHeight := height(root.right)
if leftHeight > rightHeight {
return leftHeight + 1
}
return rightHeight + 1
}Solution
Step 1: Check base case return value
The function returns -1 for nil nodes, which causes height to be off by one compared to standard definition.Step 2: Understand correct base case for height
Height of empty tree should be 0 or 0 edges; returning -1 leads to negative heights and incorrect results.Final Answer:
Returning -1 for nil node causes incorrect height calculation -> Option AQuick Check:
Base case should return 0 for nil [OK]
- Returning -1 instead of 0 for nil
- Confusing base case with leaf node
- Not adding 1 after recursive calls
Solution
Step 1: Understand combined task requirements
We need height and sum of nodes at deepest level in one function efficiently.Step 2: Evaluate approaches
Use a recursive function that returns both height and sum at deepest level by comparing left and right subtree results uses recursion returning height and sum together, avoiding multiple traversals.Step 3: Compare other options
Calculate height first, then traverse tree again to sum deepest level nodes separately does two traversals, less efficient. Use iterative BFS to find height and sum nodes at last level in one pass is valid but iterative BFS is not recursive. Use recursion to sum all nodes and ignore height calculation ignores height, so incomplete.Final Answer:
Use a recursive function that returns both height and sum at deepest level by comparing left and right subtree results -> Option CQuick Check:
Combine height and sum in one recursive pass [OK]
- Doing two separate traversals
- Ignoring sum at deepest level
- Using iterative approach when recursion asked
Ready to prove it?
Pass the test and this pattern moves unknown
