-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect_all_level_full_binary_tree_preorder_fashion.c
68 lines (58 loc) · 1.59 KB
/
connect_all_level_full_binary_tree_preorder_fashion.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
62
63
64
65
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
struct node *nextRight;
};
void connect_rec(struct node *root);
void connect(struct node *root)
{
root->nextRight=NULL;
connect_rec(root);
}
void connect_rec(struct node *root)
{
if(root==NULL)
return;
if(root->left)
root->left->nextRight=root->nextRight;
if(root->right)
root->right->nextRight=root->nextRight?root->nextRight->left:NULL;
connect_rec(root->left);
connect_rec(root->right);
}
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->nextRight = NULL;
return(node);
}
int main()
{
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
printf("Following are populated nextRight pointers in the tree "
"(-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight? root->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight? root->left->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight? root->right->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight? root->left->left->nextRight->data: -1);
getchar();
return 0;
}