Skip to content

Commit 9bf7916

Browse files
committed
Add solution #623
1 parent 2701840 commit 9bf7916

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@
472472
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
473473
621|[Task Scheduler](./0621-task-scheduler.js)|Medium|
474474
622|[Design Circular Queue](./0622-design-circular-queue.js)|Medium|
475+
623|[Add One Row to Tree](./0623-add-one-row-to-tree.js)|Medium|
475476
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
476477
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
477478
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|

solutions/0623-add-one-row-to-tree.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

Comments
 (0)