-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathThreadedTree.cpp
93 lines (80 loc) · 1.35 KB
/
ThreadedTree.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <queue>
using namespace std;
struct node
{
node *left,*right;
int key;
bool threaded;
};
node *createNode(int key)
{
node *t= new node;
t->left=NULL;
t->right=NULL;
t->key=key;
t->threaded=false;
return t;
}
void storeQueue(node *root, queue<node *> *q)
{
if(root==NULL)
return;
if(root->left)
storeQueue(root->left,q);
q->push(root);
if(root->right)
storeQueue(root->right,q);
}
void createThread(node *root, queue<node *> *q)
{
if(root==NULL)
return;
if(root->left)
createThread(root->left,q);
q->pop();
if(root->right)
createThread(root->right,q);
else
{
root->right=q->front();
root->threaded=true;
}
}
void threadify(node *root)
{
queue<node *> q;
storeQueue(root,&q);
createThread(root,&q);
}
node *leftmost(node *root)
{
while(root->left)
root=root->left; //we are at the leftmost node/leaf
return root;
}
void traverse(node *root)
{
node *t=leftmost(root);
while(t!=NULL)
{
cout << t->key << " ";
if(t->threaded)
t=t->right;
else
t=leftmost(t->right);
}
}
int main()
{
node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
threadify(root);
traverse(root);
return 0;
}