题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/*
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)
{
TreeNode *pLastNodeOfList = NULL;
ConvertNode(pRootOfTree, &pLastNodeOfList);
TreeNode *pHeadOfList = pLastNodeOfList;
while(pHeadOfList!=NULL && pHeadOfList->left!=NULL)
pHeadOfList = pHeadOfList->left;
return pHeadOfList;
}
private:
void ConvertNode(TreeNode *pNode, TreeNode **pLastNode){
if(!pNode) return;
TreeNode *pCurrent = pNode;
if(pCurrent->left)
ConvertNode(pCurrent->left, pLastNode);
pCurrent->left = *pLastNode;
if(*pLastNode)
(*pLastNode)->right = pCurrent;
*pLastNode = pCurrent;
if(pCurrent->right)
ConvertNode(pCurrent->right, pLastNode);
}
};
如有建议或其他问题,可随时给我们留言。或者到以下链接:
Star/Fork/Push 您的代码,开源仓库需要您的贡献。
请查看Coding 题目网址和收藏Accepted代码仓库,进行coding!!!