方法:中序遍历
1、使用pre与curr指针:时间复杂度O(N) 空间复杂度O(N)
class Solution {//顺序实际上为中序遍历
public:
Node* head=nullptr;
Node* pre=nullptr;
queue<Node*> que;
void inorder(Node* curr){
if(!curr) return;
inorder(curr->left);
if(pre){
curr->left = pre;
pre->right = curr;
}else head = curr;
pre = curr;
inorder(curr->right);
}
Node* treeToDoublyList(Node* root){
if(!root) return root;
inorder(root);
head->left = pre;
pre->right = head;
return head;
}
};
2、使用队列辅助保存中序遍历的结果
时间复杂度O(2N) 空间复杂度O(N)
class Solution {//顺序实际上为中序遍历
public:
Node* head=nullptr;
Node* prenode=nullptr;
queue<Node*> que;
void inorder(Node* root){
if(!root) return;
inorder(root->left);
que.push(root);
inorder(root->right);
}
Node* treeToDoublyList(Node* root) {
if(!root) return root;
inorder(root);
head = que.front();
while(!que.empty()){
root = que.front();
que.pop();
if(!que.empty()) root->right = que.front();
root->left = prenode;
prenode = root;
}
head->left = root;
root->right = head;
return head;
}
};