623. Add One Row to Tree (javascript solution)
codingpineapple
Posted on March 9, 2021
Description:
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N'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 depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
Solution:
Time Complexity : O(n)
Space Complexity: O(n)
// DFS approach
var addOneRow = function(root, v, d) {
if (d === 1) {
const node = new TreeNode(v);
node.left = root;
return node;
}
insert(v, root, 1, d);
return root;
}
function insert(val, node, depth, n) {
if (node === null)
return;
// Stop when we hit n - 1 and add the new nodes at the current level
if (depth == n - 1) {
let t = node.left;
node.left = new TreeNode(val);
node.left.left = t;
t = node.right;
node.right = new TreeNode(val);
node.right.right = t;
}
// Keep traversing down the tree if we are not on the correct level
else {
insert(val, node.left, depth + 1, n);
insert(val, node.right, depth + 1, n);
}
}
Posted on March 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 5, 2024
September 29, 2024