LeetCode: Add One Row To Tree Solution
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} 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 }1920 const recursion = function (node, depth = 1) {21 if (!node) {22 return23 }2425 if (depth === d - 1) {26 node.left = new TreeNode(v, node.left, undefined)27 node.right = new TreeNode(v, undefined, node.right)28 return29 }3031 recursion(node.left, depth + 1)32 recursion(node.right, depth + 1)33 }3435 recursion(root, 1)3637 return root38}
Comments
Loading comments...
Tags
leetcode
tree
recursion
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Coin Change
Mar 12, 2021
Previous Post
CSSBattle 1.1: Simply Square
Mar 9, 2021