Leetcode 623. Add One Row to Tree
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
. The root node is considered to have depth 1
.
The adding rule is:
depth
, for each not null tree node N
at the depth depth - 1
, create two tree nodes with value val
as N
’s left subtree root and N
’s right subtree root.N
’s original left subtree should be the left subtree of the new left subtree root.N
’s original right subtree should be the right subtree of the new right subtree root.Return the modified tree’s root.
Example:
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]
Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]
depth
is 1?
depth
is 1, then we need to add the new row at the root. This means creating a new root with the given val
and making the existing tree its left subtree.depth == 1
where we need to replace the root.(depth-1)
to insert the new nodes.Here’s the Java code to implement the solution:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
if (depth == 1) {
return new TreeNode(val, root, null);
}
insert(root, val, depth, 1);
return root;
}
private void insert(TreeNode node, int val, int depth, int currentDepth) {
if (node == null) {
return;
}
if (currentDepth == depth - 1) {
TreeNode tempLeft = node.left;
TreeNode tempRight = node.right;
node.left = new TreeNode(val, tempLeft, null);
node.right = new TreeNode(val, null, tempRight);
} else {
insert(node.left, val, depth, currentDepth + 1);
insert(node.right, val, depth, currentDepth + 1);
}
}
}
The time complexity of this approach is O(n)
, where n
is the number of nodes in the tree. This is because we need to potentially visit each node once to insert the new row at the correct depth.
depth == 1
, make a new root.depth - 1
.val
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?