#623
Add One Row to Tree
MediumTreeDepth-First SearchBreadth-First SearchBinary TreeTree TraversalLevel Order Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single traversal to reach the desired depth, making it more efficient. We can use a queue to manage the nodes at the current depth and add new nodes in one pass.
⚙️
Algorithm
3 steps- 1Step 1: If depth is 1, create a new root node with the given value and set the original tree as its left child.
- 2Step 2: Use a queue to perform a level-order traversal until reaching depth - 1.
- 3Step 3: For each node at depth - 1, create two new nodes with the given value and adjust the original children accordingly.
solution.py27 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def addOneRow(root, val, depth):
9 if depth == 1:
10 new_root = TreeNode(val)
11 new_root.left = root
12 return new_root
13 queue = [root]
14 current_depth = 1
15 while queue:
16 if current_depth == depth - 1:
17 for node in queue:
18 new_left = TreeNode(val)
19 new_right = TreeNode(val)
20 new_left.left = node.left
21 new_right.right = node.right
22 node.left = new_left
23 node.right = new_right
24 return root
25 current_depth += 1
26 queue = [child for node in queue for child in (node.left, node.right) if child]
27 return rootℹ
Complexity note: The time complexity is O(n) because we traverse each node in the tree once. The space complexity is O(n) due to the queue used for level-order traversal.
- 1Understanding tree depth is crucial for manipulating tree structures.
- 2Level-order traversal is an effective way to access nodes at specific depths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.