-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path116_populating_next_right_pointers_in_each_node.c
61 lines (55 loc) · 1.9 KB
/
116_populating_next_right_pointers_in_each_node.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <assert.h>
#include <stdlib.h>
struct TreeLinkNode {
int val;
struct TreeLinkNode *left, *right, *next;
};
void connect(struct TreeLinkNode *root) {
if(root == NULL) return;
struct TreeLinkNode* cur;
while(root->left) {
cur = root;
while(cur) {
cur->left->next = cur->right;
if(cur->next)
cur->right->next = cur->next->left;
cur = cur->next;
}
root = root->left;
}
}
int main() {
struct TreeLinkNode* root = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
root->val = 1;
root->next = NULL;
struct TreeLinkNode* node1_1 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node1_1->val = 2;
root->left = node1_1;
struct TreeLinkNode* node1_2 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node1_2->val = 3;
node1_2->next = NULL;
root->right = node1_2;
struct TreeLinkNode* node2_1 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node2_1->val = 4;
node2_1->left = node2_1->right = NULL;
struct TreeLinkNode* node2_2 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node2_2->val = 5;
node2_2->left = node2_2->right = NULL;
struct TreeLinkNode* node2_3 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node2_3->val = 6;
node2_3->left = node2_3->right = NULL;
struct TreeLinkNode* node2_4 = (struct TreeLinkNode *)malloc(sizeof(struct TreeLinkNode));
node2_4->val = 7;
node2_4->left = node2_4->right = node2_4->next = NULL;
node1_1->left = node2_1;
node1_1->right = node2_2;
node1_2->left = node2_3;
node1_2->right = node2_4;
connect(root);
assert(node1_1->next == node1_2);
assert(node2_1->next == node2_2);
assert(node2_2->next == node2_3);
assert(node2_3->next == node2_4);
assert(node2_4->next == NULL);
return 0;
}