Skip to content

Commit 3579606

Browse files
committed
"Populating Next Right Pointers in Each Node"
1 parent 55bcf55 commit 3579606

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
172172
| 119 | [Pascal's Triangle II] | [C](src/119.c) |
173173
| 118 | [Pascal's Triangle] | [C](src/118.c) |
174174
| 117 | [Populating Next Right Pointers in Each Node II] | |
175-
| 116 | [Populating Next Right Pointers in Each Node] | |
175+
| 116 | [Populating Next Right Pointers in Each Node] | [C](src/116.c) |
176176
| 115 | [Distinct Subsequences] | |
177177
| 114 | [Flatten Binary Tree to Linked List] | |
178178
| 113 | [Path Sum II] | |

src/116.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct TreeLinkNode {
5+
int val;
6+
struct TreeLinkNode *left, *right, *next;
7+
};
8+
9+
void connectHelper(struct TreeLinkNode *node, struct TreeLinkNode *sibling) {
10+
if (node == NULL) return;
11+
if (!node->left || !node->right) return;
12+
13+
/* node have two children */
14+
node->left->next = node->right;
15+
node->right->next = (sibling == NULL) ? NULL : sibling->left;
16+
17+
connectHelper(node->left, node->right);
18+
connectHelper(node->right, node->right->next);
19+
}
20+
21+
void connect(struct TreeLinkNode *root) {
22+
if (root == NULL) return;
23+
24+
root->next = NULL;
25+
connectHelper(root, NULL);
26+
}
27+
28+
int main() {
29+
struct TreeLinkNode *root = (struct TreeLinkNode *)calloc(7, sizeof(struct TreeLinkNode));
30+
root->val = 1;
31+
root->left = root + 1;
32+
root->left->val = 2;
33+
root->right = root + 2;
34+
root->right->val = 3;
35+
36+
root->left->left = root + 3;
37+
root->left->left->val = 4;
38+
root->left->right = root + 4;
39+
root->left->right->val = 5;
40+
41+
root->right->left = root + 5;
42+
root->right->left->val = 6;
43+
root->right->right = root + 6;
44+
root->right->right->val = 7;
45+
46+
connect(root);
47+
48+
return 0;
49+
}

0 commit comments

Comments
 (0)