解题思路:
二叉搜索树的中序遍历的节点顺序就是有序的。可以通过双指针法去记录前驱节点和后继节点。
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if(root==NULL) return NULL;
dfs(root);
head->left=pre;
pre->right=head;
return head;
}
private:
Node* head;
Node* pre;
void dfs(Node* cur){
if(cur==NULL) return;
dfs(cur->left);
if(pre==NULL) head=cur;
else pre->right=cur;
cur->left=pre;
pre=cur;
dfs(cur->right);
}
};