|
| 1 | +/** |
| 2 | + * 623. Add One Row to Tree |
| 3 | + * https://leetcode.com/problems/add-one-row-to-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree and two integers val and depth, add a row of nodes with value |
| 7 | + * val at the given depth depth. |
| 8 | + * |
| 9 | + * Note that the root node is at depth 1. |
| 10 | + * |
| 11 | + * The adding rule is: |
| 12 | + * - Given the integer depth, for each not null tree node cur at the depth depth - 1, create two |
| 13 | + * tree nodes with value val as cur's left subtree root and right subtree root. |
| 14 | + * - cur's original left subtree should be the left subtree of the new left subtree root. |
| 15 | + * - cur's original right subtree should be the right subtree of the new right subtree root. |
| 16 | + * - If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with |
| 17 | + * value val as the new root of the whole original tree, and the original tree is the new root's |
| 18 | + * left subtree. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * Definition for a binary tree node. |
| 23 | + * function TreeNode(val, left, right) { |
| 24 | + * this.val = (val===undefined ? 0 : val) |
| 25 | + * this.left = (left===undefined ? null : left) |
| 26 | + * this.right = (right===undefined ? null : right) |
| 27 | + * } |
| 28 | + */ |
| 29 | +/** |
| 30 | + * @param {TreeNode} root |
| 31 | + * @param {number} val |
| 32 | + * @param {number} depth |
| 33 | + * @return {TreeNode} |
| 34 | + */ |
| 35 | +var addOneRow = function(root, val, depth) { |
| 36 | + if (depth === 1) { |
| 37 | + return new TreeNode(val, root); |
| 38 | + } |
| 39 | + dfs(root, 1); |
| 40 | + |
| 41 | + return root; |
| 42 | + |
| 43 | + function dfs(node, level) { |
| 44 | + if (!node) return; |
| 45 | + if (level === depth - 1) { |
| 46 | + node.left = new TreeNode(val, node.left); |
| 47 | + node.right = new TreeNode(val, null, node.right); |
| 48 | + return; |
| 49 | + } |
| 50 | + dfs(node.left, level + 1); |
| 51 | + dfs(node.right, level + 1); |
| 52 | + } |
| 53 | +}; |
0 commit comments