-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathFlatten the BST into sorted linkedlist
72 lines (47 loc) · 1.16 KB
/
Flatten the BST into sorted linkedlist
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<bits/stdc++.h>
using namespace std;
pair<node*,node*>flatten(node*root)
{
pair<node*,node*>l;
if(root==NULL)
{
l.first=NULL;
l.second=NULL;
return l;
}
// leaf node
if(root->left==NULL && root->right==NULL)
{
l.first=l.second=root;
return l;
}
if(root->left!=NULL && root->right==NULL)
{
pair<node*,node*> p=flatten(root->left);
p.second->right=root;
l.first=p.first
l.second=root;
return l;
}
if(root->right!=NULL && root->left==NULL)
{
pair<node*,node*>p=flatten(root->right);
root->right=p.first;
l.first=root;
l.second=p.second;
return l;
}
if(root->left!=NULL && root->right!=NULL)
{
pair<node*,node*>ll=flatten(root->left);
pair<node*,node*>rl=flatten(root->ight);
ll.second->right=root;
root->right=rl.first;
l.first=ll.first;
l.second=rl.second;
return l;
}
}
int main()
{
}