输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
//递归解法
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)
{
if(pRootOfTree==nullptr)
return nullptr;
TreeNode* pLastNodeInList=nullptr;
ConvertNode(pRootOfTree,pLastNodeInList);
TreeNode* pHeadOfList=pLastNodeInList;
while(pHeadOfList->left!=nullptr)
{
pHeadOfList=pHeadOfList->left;
}
return pHeadOfList;
}
//将子树进行中序遍历并转换为双向链表
void ConvertNode(TreeNode* pNode,TreeNode* &pLastNodeInList)
{
if(pNode==nullptr)
return;
TreeNode* pCurrent=pNode;
//若左子树不为空,则将左子树转换为双向链表并且改变当前节点pNode的指向
if(pCurrent->left)
ConvertNode(pCurrent->left,pLastNodeInList);
pCurrent->left=pLastNodeInList;
if(pLastNodeInList)
pLastNodeInList->right=pCurrent;
//将左子树转换完之后,双向链表最后一个指针是当前节点
pLastNodeInList=pNode;
//若右子树不为空,则按一样步骤处理右子树
if(pCurrent->right)
ConvertNode(pCurrent->right,pLastNodeInList);
}
};