-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path116.populating-next-right-pointers-in-each-node-faster.c
More file actions
86 lines (68 loc) · 2.08 KB
/
116.populating-next-right-pointers-in-each-node-faster.c
File metadata and controls
86 lines (68 loc) · 2.08 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Node
{
int val;
struct Node *left;
struct Node *right;
struct Node *next;
};
struct Node *connect(struct Node *root)
{
if (root == NULL || root->left == NULL)
return root;
root->left->next = root->right;
if (root->next != NULL)
{
root->right->next = root->next->left;
}
connect(root->left);
connect(root->right);
return root;
}
void traversal(struct Node *root)
{
printf("%d next is %d\n", root->val, root->next == NULL ? 0 : root->next->val);
if (root->left != NULL)
{
traversal(root->left);
}
if (root->right != NULL)
{
traversal(root->right);
}
}
int main(int argc, char const *argv[])
{
struct Node *rootLeftLeft = (struct Node *)malloc(sizeof(struct Node));
rootLeftLeft->val = 4;
rootLeftLeft->left = rootLeftLeft->right = rootLeftLeft->next = NULL;
struct Node *rootLeftRight = (struct Node *)malloc(sizeof(struct Node));
rootLeftRight->val = 5;
rootLeftRight->left = rootLeftRight->right = rootLeftRight->next = NULL;
struct Node *rootRightLeft = (struct Node *)malloc(sizeof(struct Node));
rootRightLeft->val = 6;
rootRightLeft->left = rootRightLeft->right = rootRightLeft->next = NULL;
struct Node *rootRightRight = (struct Node *)malloc(sizeof(struct Node));
rootRightRight->val = 7;
rootRightRight->left = rootRightRight->right = rootRightRight->next = NULL;
struct Node *rootLeft = (struct Node *)malloc(sizeof(struct Node));
rootLeft->val = 2;
rootLeft->left = rootLeftLeft;
rootLeft->right = rootLeftRight;
rootLeft->next = NULL;
struct Node *rootRight = (struct Node *)malloc(sizeof(struct Node));
rootRight->val = 3;
rootRight->left = rootRightLeft;
rootRight->right = rootRightRight;
rootRight->next = NULL;
struct Node *root = (struct Node *)malloc(sizeof(struct Node));
root->val = 1;
root->left = rootLeft;
root->right = rootRight;
root->next = NULL;
root = connect(root);
traversal(root);
return 0;
}