-
Notifications
You must be signed in to change notification settings - Fork 0
/
378. 将二叉查找树转换成双链表.cpp
54 lines (54 loc) · 1.29 KB
/
378. 将二叉查找树转换成双链表.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
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Definition of Doubly-ListNode
* class DoublyListNode {
* public:
* int val;
* DoublyListNode *next, *prev;
* DoublyListNode(int val) {
* this->val = val;
this->prev = this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
DoublyListNode *temp;
void core(TreeNode *root)
{
if(root!=NULL)
{
core(root->left);
DoublyListNode *new_node = new DoublyListNode(root->val);
temp->next = new_node;
new_node->prev = temp;
temp = new_node;
core(root->right);
}
}
DoublyListNode* bstToDoublyList(TreeNode* root) {
// Write your code here
if(root==NULL)
return NULL;
DoublyListNode *head = new DoublyListNode(0);
temp = head;
core(root);
temp = head->next;
temp->prev = NULL;
delete head;
return temp;
}
};