题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解法
中序排序
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void GetConvertTail(TreeNode* pRootOfTree,TreeNode** pLastNode)
{
if(pRootOfTree == NULL)
{
return;
}
TreeNode* curNode = pRootOfTree;
if(curNode->left)
{
GetConvertTail(curNode->left,pLastNode);
}
curNode->left = *pLastNode;
if(*pLastNode)
{
(*pLastNode)->right = curNode;
}
*pLastNode = curNode;
if(curNode->right)
{
GetConvertTail(curNode->right,pLastNode);
}
}
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree == NULL)
{
return NULL;
}
TreeNode* result = NULL;
GetConvertTail(pRootOfTree,&result);
while(result && result->left)
{
result = result->left;
}
return result;
}
};
网友评论