-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path036-二叉搜索树与双向链表.cpp
41 lines (36 loc) · 1.14 KB
/
036-二叉搜索树与双向链表.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
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree==nullptr)
return nullptr;
TreeNode* pLastNodeInList=nullptr;
ConvertCore(pRootOfTree,&pLastNodeInList);
while(pLastNodeInList!=nullptr&&pLastNodeInList->left!=nullptr)
pLastNodeInList=pLastNodeInList->left;
return pLastNodeInList;
}
void ConvertCore(TreeNode* pRootOfTree,TreeNode** pLastNodeInList){
if(pRootOfTree==nullptr)
return;
TreeNode* currentNode=pRootOfTree;
if(currentNode->left!=nullptr)
ConvertCore(currentNode->left,pLastNodeInList);
currentNode->left=*pLastNodeInList;
if(*pLastNodeInList!=nullptr)
(*pLastNodeInList)->right=currentNode;
currentNode->left=*pLastNodeInList;
*pLastNodeInList=currentNode;
if(currentNode->right!=nullptr)
ConvertCore(currentNode->right,pLastNodeInList);
}
};