2021年03月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;
}
};
参考文献
《剑指offer 第二版》