题目27:二叉搜索树与双向链表
题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点的方向。如下图所示:
二叉树的结点定义如下:
1 struct BinaryTreeNode 2 { 3 int m_nValue; 4 BinaryTreeNode* m_pLeft; 5 BinaryTreeNode* m_pRight; 6 };
1 BinaryTreeNode* convert(BinaryTreeNode* pRootOfTree) 2 { 3 //pLastNodeList指向已经转换好的链表的最后一个结点 4 BianryTreeNode* pLastNodeInList = NULL; 5 convertNode(pRootOfTree, &pLastNodeInList); 6 //pLastNodeInList指向双向链表的尾结点,需要找到头结点 7 BianryTreeNode* pHeadOfList = pLastNodeInList; 8 while (pHeadOfList != NULL && pHeadOfList->m_pLeft != NULL) 9 pHeadOfList = pHeadOfList->m_pLeft; 10 return pHeadOfList; 11 } 12 13 void convertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeList) 14 { 15 if (pNode == NULL) 16 return; 17 BinaryTreeNode* pCurrent = pNode; 18 if (pCurrent->m_pLeft != NULL) 19 convertNode(pCurrent->m_pLeft, pLastNodeList); 20 pCurrent->m_pLeft = *pLastNodeInList; 21 if (*pLastNodeInList != NULL) 22 (*pLastNodeInList)->m_pRight = pCurrent; 23 *pLastNodeInList = pCurrent; 24 if (pCurrent->m_pRight!=NULL) 25 convertNode(pCurrent->m_pRight, pLastNodeList); 26 }