Problem 470735 · medium · Level 04 Non-Linear Data Structures

Insert a Row of Nodes at a Depth

binary tree · breadth-first search · in-place modification

Given the root of a tree, a value val and a positive integer depth, insert a complete row of new nodes with value val at that depth (the root is at depth 1). For every node p at depth depth - 1, create two new nodes valued val: the first becomes p's new left child and takes p's old left subtree as its left subtree; the second becomes p's new right child and takes p's old right subtree as its right subtree. If depth == 1, create a new root valued val whose left subtree is the whole original tree. Return the root.

Examples

       5                           5
     /   \                      /     \
    8     1                   8         1
     \   / \    ==>          / \       / \
      3 7   2               6   6     6   6
                                 \   /     \
                                  3 7       2

Input:  root = build_tree([5, 8, 1, None, 3, 7, 2]), val = 6, depth = 3
Output: tree_to_list(...) == [5, 8, 1, 6, 6, 6, 6, None, None, None, 3, 7, None, None, 2]
Explanation: 8 has no left subtree, but it still gets a new left node 6.

Input:  root = build_tree([5, 8]), val = 6, depth = 1
Output: [6, 5, None, 8]

Constraints

  • 0 <= number of nodes <= 1000
  • 1 <= depth <= (height of the tree) + 1

Goals

  • Stop a level-order walk exactly one level above the insertion depth
  • Attach old subtrees to the correct side of the new nodes
Starting Python…