1.转换成循环双向链表。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node* treeToDoublyList(Node* root)
{
if(!root) return NULL;
Node*head=NULL,*tail=NULL;
middleSort(root,head,tail);
head->left=tail;
tail->right=head;
return head;
}
void middleSort(Node*root,Node*&head,Node*&tail)
{
if(!root) return;
middleSort(root->left,head,tail);
if(!head)
{
head=root;
tail=root;
}
else{
tail->right=root;
root->left=tail;
tail=tail->right;
}
middleSort(root->right,head,tail);
}
};
转换成普通双向链表
class Solution{
public:
void middlesort(Node*root,Node*&head)
{
if(!root) return ;
middlesort(root->left)
if(!head)
{
head=root;
}
else{
head->right=root;
root->left=head;
head=head->right;
}
}
Node* treeToDoublyList(Node* root)
{
if(!root) return root;
Node* head=NULL;
middlesort(root,head);
return head;
}
};