# LeetCode: Add One Row To Tree Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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} root11 * @param {number} v12 * @param {number} d13 * @return {TreeNode}14 */15var addOneRow = function (root, v, d) {16  if (d === 1) {17    return new TreeNode(v, root)18  }19
20  const recursion = function (node, depth = 1) {21    if (!node) {22      return23    }24
25    if (depth === d - 1) {26      node.left = new TreeNode(v, node.left, undefined)27      node.right = new TreeNode(v, undefined, node.right)28      return29    }30
31    recursion(node.left, depth + 1)32    recursion(node.right, depth + 1)33  }34
35  recursion(root, 1)36
37  return root38}```

leetcode

tree

recursion

## Next Post

LeetCode: Coin Change

Mar 12, 2021

Search Posts