-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path36_convert_binary_search_tree.cc
88 lines (77 loc) · 2 KB
/
36_convert_binary_search_tree.cc
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
#include <iostream>
#include "tree_util.h"
using namespace std;
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
if (!pRootOfTree) {
return NULL;
}
TreeNode *prev_last = NULL;
convert_core(pRootOfTree, prev_last);
while (prev_last->left) {
prev_last = prev_last->left;
}
return prev_last;
}
private:
static void convert_core(TreeNode *node, TreeNode *&prev_last) {
if (node->left) {
convert_core(node->left, prev_last);
}
if (prev_last) {
prev_last->right = node;
}
node->left = prev_last;
prev_last = node;
if (node->right) {
convert_core(node->right, prev_last);
}
}
};
int main(int argc, char *argv[])
{
{
int arr[] = { 10, 6, 4, -1, -1, 8, -1, -1, 14, 12, -1, -1, 16, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
TreeNode *p = Solution().Convert(root), *q;
while (p) {
q = p->right;
cout << p->val << " ";
delete p;
p = q;
}
cout << endl;
// delete_postorder(root);
}
{
int arr[] = { 10, 9, 8, -1, -1, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
TreeNode *p = Solution().Convert(root), *q;
while (p) {
q = p->right;
cout << p->val << " ";
delete p;
p = q;
}
cout << endl;
// delete_postorder(root);
}
{
int arr[] = { 10, -1, 11, -1, 12, -1, -1 };
TreeNode* root = create_pre_order(arr, NELEM(arr));
pre_order(root);
TreeNode *p = Solution().Convert(root), *q;
while (p) {
q = p->right;
cout << p->val << " ";
delete p;
p = q;
}
cout << endl;
// delete_postorder(root);
}
return 0;
}