-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path27_ConvertBinarySearchTree.cpp
108 lines (88 loc) · 1.67 KB
/
27_ConvertBinarySearchTree.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <cstdio>
using namespace std;
struct BinaryTreeNode
{
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
void CreateTree(BinaryTreeNode ** root)
{
//BinaryTreeNode *index;
int value;
cin >> value;
if (value != 0)
{
(*root) = new BinaryTreeNode;
(*root)->value = value;
(*root)->left = NULL;
(*root)->right = NULL;
CreateTree(&(*root)->left);
CreateTree(&((*root)->right));
}
}
void ConvertNode(BinaryTreeNode *root, BinaryTreeNode **last_node)
{
if (root == NULL)
return;
BinaryTreeNode *current = root;
if (root->left != NULL)
ConvertNode(current->left, last_node);
current->left = *last_node;
if (*last_node != NULL)
(*last_node)->right = current;
*last_node = current;
if (current->right != NULL)
ConvertNode(current->right, last_node);
}
BinaryTreeNode* ConvertToList(BinaryTreeNode *root)
{
if (root == NULL)
return NULL;
BinaryTreeNode *last_node = NULL;
ConvertNode(root, &last_node);
BinaryTreeNode *head = last_node;
while (head != NULL && head->left != NULL)
head = head->left;
return head;
}
void DeleteTree(BinaryTreeNode **root)
{
if((*root) == NULL)
return ;
BinaryTreeNode *index = *root;
BinaryTreeNode *tmp = index;
while (index)
{
tmp = index;
index = index->right;
delete (tmp);
}
}
void PrintList(BinaryTreeNode *head)
{
if(head == NULL)
return ;
BinaryTreeNode *index = head;
while (index)
{
cout << index->value << " ";
index = index->right;
}
}
int main(void)
{
int n;
cin >> n;
while (n --)
{
BinaryTreeNode *root = NULL;
CreateTree(&root);
root = ConvertToList(root);
PrintList(root);
cout << endl;
DeleteTree(&root);
}
return 0;
}