在二叉树中增加一行
难度:
标签:
题目描述
给定一个二叉树的根 root
和两个整数 val
和 depth
,在给定的深度 depth
处添加一个值为 val
的节点行。
注意,根节点 root
位于深度 1
。
加法规则如下:
- 给定整数
depth
,对于深度为depth - 1
的每个非空树节点cur
,创建两个值为val
的树节点作为cur
的左子树根和右子树根。 cur
原来的左子树应该是新的左子树根的左子树。cur
原来的右子树应该是新的右子树根的右子树。- 如果
depth == 1
意味着depth - 1
根本没有深度,那么创建一个树节点,值val
作为整个原始树的新根,而原始树就是新根的左子树。
示例 1:
输入: root = [4,2,6,3,1,5], val = 1, depth = 2 输出: [4,1,1,2,null,null,6,3,1,5]
示例 2:
输入: root = [4,2,null,3,1], val = 1, depth = 3 输出: [4,2,null,1,1,3,null,null,1]
提示:
- 节点数在
[1, 104]
范围内 - 树的深度在
[1, 104]
范围内 -100 <= Node.val <= 100
-105 <= val <= 105
1 <= depth <= the depth of tree + 1
代码结果
运行时间: 27 ms, 内存: 17.5 MB
/*
* Problem: Add a row of nodes with value val at the given depth in a binary tree.
* Input: root - the root of the tree, val - the value of the new nodes, depth - the depth where the new nodes are added.
* Output: The modified tree root after adding the new nodes.
*
* Approach:
* 1. If depth == 1, create a new root node with value val, and set the original tree as its left child.
* 2. Use a Stream to iterate over the nodes, collecting them at depth - 1.
* 3. For each collected node, create two new nodes with value val as the left and right children.
* 4. Set the original left and right children of the node as the children of the newly created nodes respectively.
*/
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) {
TreeNode newRoot = new TreeNode(val);
newRoot.left = root;
return newRoot;
}
List<TreeNode> nodesAtDepth = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int currentDepth = 1;
while (!queue.isEmpty() && currentDepth < depth - 1) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
currentDepth++;
}
nodesAtDepth = queue.stream().collect(Collectors.toList());
nodesAtDepth.forEach(node -> {
TreeNode newLeft = new TreeNode(val);
TreeNode newRight = new TreeNode(val);
newLeft.left = node.left;
newRight.right = node.right;
node.left = newLeft;
node.right = newRight;
});
return root;
}
解释
方法:
这个题解采用递归的方式来解决问题。主要思路是通过递归遍历二叉树,当到达指定深度 depth-1 时,创建两个新节点,将原有的左右子树挂载到新创建的节点上,然后将新节点作为当前节点的新的左右子节点。如果 depth 为1,则直接创建一个新节点作为根节点,原有的整棵树作为新根节点的左子树。
时间复杂度:
O(n)
空间复杂度:
O(h),其中 h 为二叉树的高度,h ∈ [log(n), n]
代码细节讲解
🦆
在递归函数中,为什么要在递归调用左右子树之前先创建新的左右子节点,这样的顺序对最终的树结构有何影响?
▷🦆
当递归遍历到非目标深度节点时,函数`dp`是否进行了不必要的递归调用,能否通过优化减少这些调用以提高效率?
▷🦆
在递归过程中,你是如何确保不会对depth变量的值造成意外的修改,尤其是在多次递归调用中?
▷🦆
题解中提到,如果`depth`为1,则创建一个新的根节点。这种情况下,原始树的右子树会发生什么变化?
▷