题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
完整代码:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
//声明pLastNodeInlist变量,用于记录转换后双向链表的尾节点
TreeNode *pLastNodeInlist = nullptr;
//传入BST的树根,传入转换后的双向链表的尾节点,从而改掉这个指针
ConvertNode(pRootOfTree, &pLastNodeInlist);
//从尾节点向前寻找头节点
TreeNode *pHeadOfList = pLastNodeInlist;
//只要节点非空,且其左侧节点为非空
while(pHeadOfList != nullptr && pHeadOfList->left != nullptr)
pHeadOfList = pHeadOfList->left;
//返回双向链表的头节点
return pHeadOfList;
}
private:
void ConvertNode(TreeNode* pNode, TreeNode **pLastNodeInlist)
{
//检查输入的合法性
if(pNode == nullptr)
return ;
//定义当前节点
TreeNode *pCurrent = pNode;
/**********中序遍历*********/
//判断左子树的存在
if(pCurrent->left != nullptr)
//对左子树进行转换
ConvertNode(pCurrent->left,pLastNodeInlist);
//当前节点的左指针应该指向链表的尾节点
pCurrent->left = *pLastNodeInlist;
//判断*pLastNodeInlist是否为空
if(*pLastNodeInlist != nullptr)
(*pLastNodeInlist)->right = pCurrent;
//更新链表最右节点指针为当前节点
*pLastNodeInlist = pCurrent;
//判断右子树是否存在
if(pCurrent->right != nullptr)
//对右子树进行转换
ConvertNode(pCurrent->right, pLastNodeInlist);
}
};