623 Add One Row to Tree
1. Question
Given the root of a binary tree, then valuev
and depthd
, you need to add a row of nodes with valuev
at the given depthd
. The root node is at depth 1.
The adding rule is: given a positive integer depthd
, for each NOT null tree nodesN
in depthd-1
, create two tree nodes with valuev
asN's
left subtree root and right subtree root. AndN's
original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depthd
is 1 that means there is no depth d-1 at all, then create a tree node with valuevas the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
Example 2:
Note:
The given d is in range [1, maximum depth of the given tree + 1].
The given binary tree has at least one tree node.
2. Implementation
(1) BFS
(2) DFS
3. Time & Space Complexity
BFS: 时间复杂度O(n), 空间复杂度: O(w)
DFS: 时间复杂度O(n), 空间复杂度: O(d), d是输入里的d
Last updated