-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
71 lines (52 loc) · 1.23 KB
/
Copy pathmain.cpp
File metadata and controls
71 lines (52 loc) · 1.23 KB
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
// 将一个二叉搜索树转化为双向链表, 不准使用额外空间.
#include <cstddef>
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(nullptr), right(nullptr) {
}
};
void ConvertNode(TreeNode *root, TreeNode **lastNode)
{
if (!root)
return;
TreeNode *currentNode = root;
if (currentNode->left)
ConvertNode(currentNode->left, lastNode);
currentNode->left = *lastNode;
if (*lastNode)
(*lastNode)->right = currentNode;
*lastNode = currentNode;
if (currentNode->right)
ConvertNode(currentNode->right, lastNode);
}
TreeNode* Convert(TreeNode* pRootOfTree)
{
TreeNode *lastNode = nullptr;
ConvertNode(pRootOfTree, &lastNode);
TreeNode *headOfList = lastNode;
while (headOfList && headOfList->left)
headOfList = headOfList->left;
return headOfList;
}
int main()
{
TreeNode *root = new TreeNode(8);
TreeNode *root1 = new TreeNode(6);
TreeNode *root2 = new TreeNode(5);
TreeNode *root3 = new TreeNode(7);
TreeNode *root4 = new TreeNode(10);
TreeNode *root5 = new TreeNode(9);
TreeNode *root6 = new TreeNode(11);
root->left = root1;
root->right = root4;
root1->left = root2;
root1->right = root3;
root4->left = root5;
root4->right = root6;
Convert(root);
return 0;
}