-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_to_double_LL.cpp
More file actions
72 lines (61 loc) · 1.6 KB
/
binary_tree_to_double_LL.cpp
File metadata and controls
72 lines (61 loc) · 1.6 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
#include<stdio.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
//start function
struct node * to_doubly(struct node *root);
//main logic(LEFT-RIGHT-MERGE)
struct node * binary_tree_to_doubly_LL(struct node *root, int direction);
//connect a node to child nodes
void merge(struct node *root);
/*
Making a node with two childs as doubly LL.
*/
void connect(struct node *root)
{
if (root->left != NULL)
root->left->right = root;
if (root->right != NULL)
root->right->left = root;
}
//Going in the order of postfix notation(LEFT-RIGHT-VISIT) and connecting the nodes.
//direction tells whether the last call is going left(1) or right(2)
struct node * binary_tree_to_doubly_LL(struct node *root, int direction)
{
if (root == NULL)
{
return NULL;
}
//connecting left sub tree of a node
root->left = binary_tree_to_doubly_LL(root->left, 1);
//connecting right sub tree of a node
root->right = binary_tree_to_doubly_LL(root->right, 2);
//connect the node with left connected subtree and right connected sub tree
connect(root);
//if last call is left we have to return the right most connected node
if (direction == 1 && root->right != NULL)
{
while (root->right != NULL)
{
root = root->right;
}
}
//if last call is right we have to return the left most connected node
else if (direction == 2 && root->left != NULL)
{
while (root->left != NULL)
{
root = root->left;
}
}
return root;
}
struct node * to_doubly(struct node *root)
{
//to get the left most connected node we are sending the direction as right
root = binary_tree_to_doubly_LL(root, 2);
return root;
}