思路:
设置一个指针变量 为pLastNode=nullptr;为链表的最后一个节点;
递归的方式逐渐找到它的前一个节点;
按照中序遍历的方式;
先往左子树递归查找;
if(cur->left)pLastNode=helper(cur->left,pLastNode);
再处理根节点;
cur->left=pLastNode;
if(pLastNode)
pLastNode ->right=cur;
pLastNode =cur;
再处理右子树;
if(cur->right)pLastNode=helper(cur->right,pLastNode);
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode *convertToList(TreeNode* pRootOfTree,TreeNode*lastNodeInList )
{
if(pRootOfTree==nullptr)return nullptr;
//中序遍历 所以先处理左子树;
//记录当前结点;
TreeNode *cur=pRootOfTree;
if(cur->left)
lastNodeInList=convertToList(pRootOfTree->left,lastNodeInList);
//处理当前结点;
//当前结点的左指针指向已经转换链表的部分的最后一个结点;
cur->left=lastNodeInList;
//已经转换好成链表的部分的最后一个结点的右指针指向当前结点;
if(lastNodeInList)
lastNodeInList->right=cur;
lastNodeInList=cur;
if(cur->right)
lastNodeInList=convertToList(pRootOfTree->right,lastNodeInList);
return lastNodeInList;
}
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree==nullptr)return nullptr;
//记录链表的饿最后一个结点;
TreeNode *lastNodeInList=nullptr;
lastNodeInList=convertToList(pRootOfTree,lastNodeInList);
//找到链表的头结点;
TreeNode *pHead=lastNodeInList;
while(pHead&&pHead->left)
pHead=pHead->left;
return pHead;
}
};