二叉搜索树,自然就是中序遍历,然后就是构建双向链表就可以了。构建双向链表部分有点忘记,又看了看才明白。然后就干就好了。
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(root == nullptr) return nullptr;
Node* head = nullptr, *tail = nullptr;
// 中序遍历
build(root, head, tail);
head->left = tail;
tail->right = head;
return head;
}
void build(Node* root, Node* &head, Node* &tail){
if(root){
// 左
build(root->left, head, tail);
// 中
if(head == nullptr){
head = tail = root;
}else{
tail->right = root;
root->left = tail;
tail = root;
}
// 右
build(root->right, head, tail);
}
}
};
就是复习一下链表部分,剩下就没啥了。
二叉搜索树——剑指 Offer 36. 二叉搜索树与双向链表
原文:https://www.cnblogs.com/lzyrookie/p/14687958.html