Skip to content

Commit bc60a46

Browse files
committedDec 30, 2021
Add solution #116
1 parent b427cdc commit bc60a46

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy|
5555
111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy|
5656
112|[Path Sum](./0112-path-sum.js)|Easy|
57+
116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium|
5758
118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy|
5859
119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy|
5960
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 116. Populating Next Right Pointers in Each Node
3+
* https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
4+
* Difficulty: Medium
5+
*
6+
* You are given a perfect binary tree where all leaves are on the same level, and
7+
* every parent has two children. The binary tree has the following definition:
8+
*
9+
* Populate each next pointer to point to its next right node. If there is no next
10+
* right node, the next pointer should be set to NULL.
11+
*
12+
* Initially, all next pointers are set to NULL.
13+
*/
14+
15+
/**
16+
* // Definition for a Node.
17+
* function Node(val, left, right, next) {
18+
* this.val = val === undefined ? null : val;
19+
* this.left = left === undefined ? null : left;
20+
* this.right = right === undefined ? null : right;
21+
* this.next = next === undefined ? null : next;
22+
* };
23+
*/
24+
25+
/**
26+
* @param {Node} root
27+
* @return {Node}
28+
*/
29+
var connect = function(root) {
30+
const order = [];
31+
traverse(order, root);
32+
for (let level of order) {
33+
for (let i = 0; i < level.length - 1; i++) {
34+
level[i].next = level[i + 1];
35+
}
36+
}
37+
return root;
38+
};
39+
40+
function traverse(order, node, level = 0) {
41+
if (!node) {
42+
return [];
43+
}
44+
45+
order[level] = order[level] || [];
46+
order[level].push(node);
47+
48+
traverse(order, node.left, level + 1);
49+
traverse(order, node.right, level + 1);
50+
}

0 commit comments

Comments
 (0)
Please sign in to comment.