踩了一个坑,尾部结点和头结点需要连一下,因为这个坑。。runtimeerror了好久。。。
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(!root) return root;
Node* head = NULL, *tail = NULL;
// return root;
Node* ans = treeToDoublyList(root, head, tail);
if(tail)tail->right = head;
if(head)head->left = tail;
// return ans;
// cout << "ans:" << ans->val << endl;
Node* ret = ans;
// ans->left = NULL;
// ans->right = NULL;
// while (ret) {
// cout << "&:" << ret->val << " pre:" << (ret->left == NULL ? -1:ret->left->val) << " next:" << (ret->right == NULL? -1: ret->right->val) << endl;
// ret = ret->right;
// }
return ans;
}
Node* treeToDoublyList(Node*root, Node *&head , Node *&tail) {
// return root;
if(!root) {
// head = root;
// tail = root;
return root;
}
// cout << "-->" << root->val << endl;
Node* cur = NULL, *left_tail = NULL;
if(root->left){
cur = treeToDoublyList(root->left, cur, left_tail);
left_tail->right = root;
root->left = left_tail;
tail = root;
head = cur;
} else {
cur = root;
left_tail = root;
head = root;
tail = root;
}
//head用于
Node*new_head = NULL, *new_tail=NULL;
if(root->right) {
root->right = treeToDoublyList(root->right, new_head, new_tail);
new_head->left = root;
tail = new_tail;
} else {
new_tail = root;
new_head = root;
tail = root;
}
if(!head || head->val > cur->val) {
head = cur;
}
if(!tail || tail->val < new_tail->val) {
tail = new_tail;
}
// cout << "root:" << root->val << " head:" << head->val << " tail:" << tail->val << endl;
// cout << "<--" << root->val << endl;
return cur;
}
};