将一个二叉查找树转换成排好序的双向链表,不能创建中间节点,只能调整节点的指向
struct Node
{
int value;
Node* left;
Node* right;
Node(int value)
{
this->value = value;
left = NULL;
right = NULL;
}
};
struct HeadTail
{
Node* head;
Node* tail;
HeadTail()
{
head = NULL;
tail = NULL;
}
};
HeadTail convert(Node* root)
{
HeadTail result;
if (root == NULL)
return result;
result.head = root;
result.tail = root;
if (root->left != NULL)
{
HeadTail leftResult = convert(root->left);
root->left = leftResult.tail; //将当前根节点的left指向左子树的链表尾
leftResult.tail->right = root; //将左子树的链表尾的right指向当前根节点
result.head = leftResult.head; //将返回结果中的链表头更新为左子树的链表头
}
if (root->right != NULL)
{
HeadTail rightResult = convert(root->right);
root->right = rightResult.head; //同上
rightResult.head->left = root;
result.tail = rightResult.tail;
}
return result;
}