Add One Row to Tree LeetCode solution in JavaScript

1
/**
2
* Definition for a binary tree node.
3
* function TreeNode(val, left, right) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.left = (left===undefined ? null : left)
6
* this.right = (right===undefined ? null : right)
7
* }
8
*/
9
/**
10
* @param {TreeNode} root
11
* @param {number} val
12
* @param {number} depth
13
* @return {TreeNode}
14
*/
15
var addOneRow = function (root, val, depth) {
16
if (depth === 1) return new TreeNode(val, root);
17

18
const refactor = (node = root, currentDep = 1) => {
19
if (!node) return;
20
if (currentDep === depth - 1) {
21
const { left, right } = node;
22
node.left = new TreeNode(val, left);
23
node.right = new TreeNode(val, null, right);
24
}
25
refactor(node.left, currentDep + 1);
26
refactor(node.right, currentDep + 1);
27
};
28
refactor();
29
return root;
30
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0