题目:输入一棵二叉搜索树,将其转为排序的双向链表,且要求不能创建任何新的结点,只能调整树中结点指针的指向。
二叉树结点定义如下:
struct BinaryTreeNode{
int value;
BinaryTreeNode *pLeft;
BinaryTreeNode *pRight;
};
思路:由于是二叉搜索树,因此其中序遍历算法可以按照从小到大的顺序遍历二叉树的每个结点。在把左、右子树都转换成排序的双向链表之后再和根节点连接起来,整棵二叉树也就转换成了排序的双向链表。
代码实现:
BinaryTreeNode* BinaryTree2List( BinaryTreeNode* pRoot ){
BinaryTreeNode *pLastNode = NULL;
ConvertNode( pRoot, &pLastNode );
BinaryTreeNode* pHeadNode = pLastNode;
while( pHeadNode != NULL && pHeadNode->pLeft != NULL){
pLastNode = pLastNode->pLeft;
}
return pHeadNode;
}
void ConvertNode( BinaryTreeNode* pRoot, BinaryTreeNode** pLastNode ){
if( pRoot == NULL )
return;
BinaryTreeNode *currentNode = pRoot;
if( currentNode->pLeft )
ConvertNode(currentNode->pLeft, *pLastNode );
currentNode->pLeft = *pLastNode;
if( *pLastNode != NULL )
*pLastNode->pRight = currentNode;
*pLastNode = currentNode;
if( currentNode->pRight )
ConvertNode(currentNode->pRight, *pLastNode );
}