-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend_all_zero_nodes_to_bootom_of_the_binary_tree.cpp
More file actions
84 lines (65 loc) · 1.64 KB
/
Copy pathsend_all_zero_nodes_to_bootom_of_the_binary_tree.cpp
File metadata and controls
84 lines (65 loc) · 1.64 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
#include <stdio.h>
#include <malloc.h>
/* nodes for queue and tree node*/
struct node {
int key;
struct node * left;
struct node * right;
};
/* function for creating new node of tree*/
struct node *newNode(int data)
{
struct node *node = (struct node *)malloc(sizeof(struct node));
node->key = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void sendZeroNodesToBottom(struct node * root){
if(root == NULL){
return ;
}
sendZeroNodesToBottom(root->left);
if(root->key == 0) if(root->left && root->left->key != 0) {root->key = root->left->key;root->left->key = 0;}
if(root->key == 0) if(root->right && root->right->key != 0){root->key = root->right->key;root->right->key = 0;}
sendZeroNodesToBottom(root->right);
}
void inOrderTraversal(struct node * root){
if(root == NULL){
return ;
}
inOrderTraversal(root->left);
printf("%d ",root->key);
inOrderTraversal(root->right);
}
void sinkNodes(struct node * root,int n){
for (int i = 0; i < n; ++i) {
sendZeroNodesToBottom(root);
}
inOrderTraversal(root);
}
// main function
int main()
{
/* Construct below tree
0
/ \
/ \
1 0
/ \
/ \
0 2
/ \
/ \
3 4
*/
node* root = newNode(0);
root->left = newNode(1);
root->right = newNode(0);
root->right->left = newNode(0);
root->right->right = newNode(2);
root->right->left->left = newNode(3);
root->right->left->right = newNode(4);
sinkNodes(root,2);
return 0;
}