二叉搜索树进行中序遍历即是符合要求的链表形式,最后只需要调整相应指针即可。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
void scan(TreeNode * phead ,vector<TreeNode *> & savetree)
{
if(phead->left!=nullptr)
scan(phead->left,savetree);
savetree.push_back(phead);
if(phead->right!=nullptr)
scan(phead->right,savetree);
}
class Solution {
private:
vector<TreeNode *> savetree;
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree==nullptr)
return nullptr;
if(pRootOfTree->left==nullptr&&pRootOfTree->right==nullptr)
return pRootOfTree;
//中序遍历并将各节点指针保存到vaector中
scan(pRootOfTree,savetree);
//调整指针
int VSize=savetree.size();
savetree[0]->left=nullptr;
savetree[0]->right=savetree[1];
for(int i=1;i<VSize-1;i++)
{
savetree[i]->left=savetree[i-1];
savetree[i]->right=savetree[i+1];
}
savetree[VSize-1]->left=savetree[VSize-2];
savetree[VSize-1]->right=nullptr;
return savetree[0];
}
};