Article Directory
Method 1: In-order traversal: time O(n), space O(n)
Problem-solving ideas:
- The in-order traversal of the binary search tree is an increasing sequence
- Therefore, to traverse the binary tree, the predecessor node needs to be recorded before backtracking
- Link the predecessor node and the current node after the left tree backtracking
answer
- Record a head node head and predecessor node prev, and traverse the binary tree in order
- Judge when backtracking on the left tree, if head is empty, it means that the head node with the smallest value has been reached, let head = prev = root
- If the head is not empty, point the left tree of root to prev and the right tree of prev to root, and adjust prev to point to root
- Traverse the right tree, link the head and tail pointer fields after the recursion ends
/*
// 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* head = nullptr, *pre = nullptr;
Node* treeToDoublyList(Node* root)
{
if (root == nullptr)
return root;
exchangeTree(root);
// 递归结束pre指向的就是最后一个节点,因此不需要通过返回值找最后的节点
head->left = pre;
pre->right = head;
return head;
}
void exchangeTree(Node* root)
{
if (root->left)
exchangeTree(root->left);
if (head == nullptr)
{
pre = head = root;
}
else
{
root->left = pre;
pre->right = root;
pre = root;
}
if (root->right)
exchangeTree(root->right);
}
};