Intuition
Just list all nodes with height height - 1
and insert a new layer with the given rules.
Approach
Use a queue
to store all nodes with the same height, and use BFS to update the nodes,
once we reach the height height - 1
, we add a new layer with the given val
for each node
:
- Create a new left child with the given
(val, node->left, nullptr)
- Create a new right child with the given
(val, nullptr, node->right)
Complexity
Time complexity: iterate all nodes of height
height - 1
$$O(n)$$Space complexity: storing all nodes of height
height - 1
$$O(n)$$
Code
|
|