思路:开始想的要左右分开处理,越想越复杂,其实按照中序遍历的方式只需要执行
- pre->right = cur;
- cur->left= pre;
另外一种更粗暴的方式是直接中序遍历存下来再进行指针操作
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node() {}
Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}
Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/
class Solution {
public:
Node *pre = nullptr, *head = nullptr;
void tree_to_list(Node *root) {
if (root == nullptr) {
return;
}
tree_to_list(root->left);
if (!pre) { // pre 未更新,最左节点
head = root;
} else {
pre->right = root;
root->left = pre;
}
pre = root;
tree_to_list(root->right);
}
Node* treeToDoublyList(Node* root) {
if (root == nullptr) {
return root;
}
pre = head = nullptr;
tree_to_list(root);
head->left = pre;
pre->right = head;
return head;
}
};