//将一个二叉搜索树转换成一个排序的双向链表,
//不能创建新节点,只能调整指针指向
这里会用到二叉搜索树的中序遍历,
#include<stack>
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)
{
typedef TreeNode* pNode;
if (pRootOfTree == NULL)
return NULL;
stack<pNode> s1;
pNode pCur = pRootOfTree;
pNode pNext = NULL;
pNode pPre = NULL;
pNode pHead = NULL;
while (pCur || !s1.empty())
{
while (pCur)
{
s1.push(pCur);
pCur = pCur->left;
}
pCur = s1.top();
pCur->left = pNext;
if (pNext == NULL)
pHead = pCur;
pNext = pCur;
s1.pop();
pPre = pCur;
pCur = pCur->right;
}
pPre->right = NULL;
pNext = pPre;
pCur = pNext->left;
while (pCur)
{
pCur->right = pNext;
pNext = pCur;
pCur = pCur->left;
}
return pHead;
}
};