题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表
要求排序可以想到中序遍历,把根节点的左右子树都转换成排序好的双向链表,再将根节点左子树的最大值,右子树的最小值与根节点相连。
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
TreeNode *lastnode=NULL;
convertnode(pRootOfTree,lastnode);
TreeNode *headnode=lastnode;
while(headnode!=NULL&&headnode->left!=NULL)
headnode=headnode->left;
return headnode;
}
void convertnode(TreeNode* pnode,TreeNode* &plastnode){
if(pnode==NULL)
return ;
TreeNode *pcurrent=pnode;
if(pcurrent->left!=NULL)
convertnode(pcurrent->left,plastnode);
pcurrent->left=plastnode;
if(plastnode!=NULL)
(plastnode)->right=pcurrent;
plastnode=pcurrent;
if(pcurrent->right!=NULL)
convertnode(pcurrent->right,plastnode);
}
};