面试题36:二叉搜索树与双向链表
输入一棵二叉搜索树,将该二又搜索树转换成一个排序的双向 链表。
要求不能创建任何新的节点,只能调整树中节点指针的指向。
力扣链接:
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
class Solution
{
public:
Node* treeToDoublyList(Node* root)
{
if(root == nullptr)
return nullptr;
dfs(root);
head->left = pre;
pre->right = head;
return head;
}
private:
Node *pre, *head;
void dfs(Node* cur)
{
if(cur == nullptr)
return;
dfs(cur->left);
if(pre != nullptr)
pre->right = cur;
else
head = cur;
cur->left = pre;
pre = cur;
dfs(cur->right);
}
};