/*
// 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 *head = NULL, *tail = NULL, *pre = NULL;
void inOrder(Node* root) {
if(!root) return ;
inOrder(root->left);
tail = root;
if(!pre) head = root;
else{
root->left = pre;
pre->right = root;
}
pre = root;
inOrder(root->right);
}
Node* treeToDoublyList(Node* root) {
if(!root) return NULL;
inOrder(root);
head->left = tail;
tail->right = head;
return head;
}
};
/*
// 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:
queue<Node*> Q;
void inOrder(Node* root) {
if(!root) return ;
inOrder(root->left);
Q.push(root);
inOrder(root->right);
}
Node* treeToDoublyList(Node* root) {
if(!root) return NULL;
inOrder(root);
Node *head = Q.front(), *now_p;
Q.pop();
Node* last_p = head;
while(!Q.empty()) {
now_p = Q.front();
Q.pop();
if(last_p) {
now_p->left = last_p;
last_p->right = now_p;
}
last_p = now_p;
}
head->left = now_p;
now_p->right = head;
return head;
}
};