二叉搜索树与双向链表

Desicription

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

Solution

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
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
private:
TreeNode* pre = nullptr;
TreeNode* res = nullptr;
void Dfs(TreeNode* root) {
if(root == nullptr) {
return ;
}
Dfs(root->left);
if(pre == nullptr) {
pre = root;
root->left = nullptr;
res = pre;
} else {
root->left = pre;
pre->right = root;
pre = root;
}
Dfs(root->right);
}
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
Dfs(pRootOfTree);
return res;
}
};