-
Notifications
You must be signed in to change notification settings - Fork 175
/
binaryTreeToDLL.cpp
75 lines (70 loc) · 1.5 KB
/
binaryTreeToDLL.cpp
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
// This function should return head to the DLL
class Solution
{
public:
// Function to convert binary tree to doubly linked list and return it.
Node *prev = NULL;
Node *bToDLL(Node *root)
{
// your code here
if (!root)
return root;
Node *head = bToDLL(root->left);
if (prev == NULL)
head = root;
else
{
prev->right = root;
root->left = prev;
}
prev = root;
bToDLL(root->right);
return head;
}
// method 2
// using _SPACE
public:
//Function to convert binary tree to doubly linked list and return it.
vector<int> v;
void inOrder(Node *root){
if(!root)
return;
else{
inOrder(root->left);
v.push_back(root->data);
inOrder(root->right);
}
}
Node * bToDLL(Node *root)
{
inOrder(root);
int n = v.size();
Node *head = new Node();
head->data = v[0];
Node *temp = head;
head->right = NULL;
head->left = NULL;
for(int i=1;i<n;i++){
Node *k = new Node();
k->data = v[i];
k->left = temp;
k->right = NULL;
temp->right = k;
temp = k;
}
return head;
}
};