LeetCode刷题实战426:将二叉搜索树转化为排序的双向链表
解题
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(!root) return root;
Node* cur = root;
stackstk;
Node* head = NULL;
Node* prev = NULL;
while(cur || !stk.empty()){
if(cur){
stk.push(cur);
cur = cur->left;
}else{
cur = stk.top();
stk.pop();
if(!head) head = cur;
if(prev){
prev->right = cur;
cur->left = prev;
}
prev = cur;
cur = cur->right;
}
}
head->left = prev;
prev->right = head;
return head;
}
};
评论