Jueves 11 de marzo de 2021, hace buen tiempo [No lamentes el pasado, no desperdicies el presente, no temas el futuro]
Contenido de este artículo
1. Introducción
Sword se refiere a la Oferta 36. Árbol de búsqueda binaria y lista doblemente enlazada
2. Solución del problema (inspeccionar el recorrido en orden, es necesario almacenar el nodo anterior)
El orden intermedio atraviesa cada nodo y almacena el nodo anterior al mismo tiempo para completar la construcción de la lista doblemente enlazada.
2.1 Recurrencia
class Solution {
public:
Node* pre, *head;
Node* treeToDoublyList(Node* root) {
if(root==nullptr) return nullptr;
dfs(root);
// 要求是双向循环链表,所以接上头和尾
head->left = pre;
pre->right = head;
return head;
}
void dfs(Node* cur){
if(cur==nullptr) return;
dfs(cur->left);
// 核心操作在这里
if(pre!=nullptr) pre->right = cur;
else head = cur;
cur->left = pre;
pre = cur;
dfs(cur->right);
}
};
2.2 Iteración
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(root==nullptr) return root;
stack<Node*> st;
Node* cur = root, *pre = nullptr, *head = nullptr;
while(cur || !st.empty()){
if(cur){
st.push(cur);
cur = cur->left;
}
else{
cur = st.top();
st.pop();
if(pre!=nullptr) pre->right = cur;
else head = cur;
cur->left = pre;
pre = cur;
cur = cur->right;
}
}
head->left = pre;
pre->right = head;
return head;
}
};
referencias
"Oferta de Sword Finger Segunda Edición"