题目:输入一颗二叉搜索树,将该二叉搜索转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路:中序遍历。(滴滴2面面试题)
struct BinaryTreeNode{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
BinaryTreeNode* Convert(BinaryTreeNode* pRoot){
BinaryTreeNode *pLastNodeInList = NULL;
ConvertNode(pRoot, &pLastNodeInList);
//pLastNodeInList指向双向链表的尾节点
BinaryTreeNode *pHeadOfList = pLastNodeInList;
while (pHeadOfList!=NULL&&pHeadOfList->left!=NULL){
pHeadOfList = pHeadOfList->left;
}
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode,BinaryTreeNode** pLastNodeInList){
if (pNode == NULL)
return;
BinaryTreeNode *pCurrent = pNode;
if (pCurrent->left != NULL)
ConvertNode(pCurrent->left,pLastNodeInList);
pCurrent->left = *pLastNodeInList;
if (*pLastNodeInList != NULL)
(*pLastNodeInList)->right = pCurrent;
*pLastNodeInList = pCurrent;
if (pCurrent->right != NULL)
ConvertNode(pCurrent->right,pLastNodeInList);
}