Add One Row to Tree — LeetCode 623 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#623
Reading time
4 min

The problem

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth. Note that the root node is at depth 1.

Example

Input
root = [4,2,6,3,1,5], val = 1, depth = 2
Output
[4,1,1,2,null,null,6,3,1,5]

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def addOneRow(
        self, root: Optional[TreeNode], val: int, depth: int
    ) -> Optional[TreeNode]:
        def dfs(root, d):
            if root is None:
                return
            if d == depth - 1:
                root.left = TreeNode(val, root.left, None)
                root.right = TreeNode(val, None, root.right)
                return
            dfs(root.left, d + 1)
            dfs(root.right, d + 1)

        if depth == 1:
            return TreeNode(val, root)
        dfs(root, 1)
        return root

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 623. Add One Row to Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 623. Add One Row to Tree?
LeetCode 623. Add One Row to Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 623. Add One Row to Tree?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 623. Add One Row to Tree?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 623. Add One Row to Tree cover?
LeetCode 623. Add One Row to Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview