2021年3月11日木曜日天気は良い[過去を嘆いたり、現在を無駄にしたり、未来を恐れたりしないでください]
1.はじめに
2.問題解決(順序どおりのトラバーサルを検査し、前のノードを保存する必要があります)
ミドルオーダーは各ノードをトラバースし、同時に前のノードを格納して、二重リンクリストの作成を完了します。
2.1再帰
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反復
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;
}
};
参照
「ソードフィンガーオファー第2版」