struct BSTreeNode // a node in the binary search tree{int m_nValue; // value of nodeBSTreeNode *m_pLeft; // left child of nodeBSTreeNode *m_pRight; // right child of node};
思路一對應(yīng)的代碼:
///
// Covert a sub binary-search-tree into a sorted double-linked list
// Input: pNode - the head of the sub tree
// asRight - whether pNode is the right child of its parent
// Output: if asRight is true, return the least node in the sub-tree
// else return the greatest node in the sub-tree
///
BSTreeNode* ConvertNode(BSTreeNode* pNode, bool asRight)
{if(!pNode)return NULL;BSTreeNode *pLeft = NULL;BSTreeNode *pRight = NULL;// Convert the left sub-treeif(pNode->m_pLeft)pLeft = ConvertNode(pNode->m_pLeft, false);// Connect the greatest node in the left sub-tree to the current nodeif(pLeft){pLeft->m_pRight = pNode;pNode->m_pLeft = pLeft;}// Convert the right sub-treeif(pNode->m_pRight)pRight = ConvertNode(pNode->m_pRight, true);// Connect the least node in the right sub-tree to the current nodeif(pRight){pNode->m_pRight = pRight;pRight->m_pLeft = pNode;}BSTreeNode *pTemp = pNode;// If the current node is the right child of its parent, // return the least node in the tree whose root is the current nodeif(asRight){while(pTemp->m_pLeft)pTemp = pTemp->m_pLeft;}// If the current node is the left child of its parent, // return the greatest node in the tree whose root is the current nodeelse{while(pTemp->m_pRight)pTemp = pTemp->m_pRight;}return pTemp;
}///
// Covert a binary search tree into a sorted double-linked list
// Input: the head of tree
// Output: the head of sorted double-linked list
///
BSTreeNode* Convert(BSTreeNode* pHeadOfTree)
{// As we want to return the head of the sorted double-linked list,// we set the second parameter to be truereturn ConvertNode(pHeadOfTree, true);
}
思路二對應(yīng)的代碼:
///
// Covert a sub binary-search-tree into a sorted double-linked list
// Input: pNode - the head of the sub tree
// pLastNodeInList - the tail of the double-linked list
///
void ConvertNode(BSTreeNode* pNode, BSTreeNode*& pLastNodeInList)
{if(pNode == NULL)return;BSTreeNode *pCurrent = pNode;// Convert the left sub-treeif (pCurrent->m_pLeft != NULL)ConvertNode(pCurrent->m_pLeft, pLastNodeInList);// Put the current node into the double-linked listpCurrent->m_pLeft = pLastNodeInList; if(pLastNodeInList != NULL)pLastNodeInList->m_pRight = pCurrent;pLastNodeInList = pCurrent;// Convert the right sub-treeif (pCurrent->m_pRight != NULL)ConvertNode(pCurrent->m_pRight, pLastNodeInList);
}///
// Covert a binary search tree into a sorted double-linked list
// Input: pHeadOfTree - the head of tree
// Output: the head of sorted double-linked list
///
BSTreeNode* Convert_Solution1(BSTreeNode* pHeadOfTree)
{BSTreeNode *pLastNodeInList = NULL;ConvertNode(pHeadOfTree, pLastNodeInList);// Get the head of the double-linked listBSTreeNode *pHeadOfList = pLastNodeInList;while(pHeadOfList && pHeadOfList->m_pLeft)pHeadOfList = pHeadOfList->m_pLeft;return pHeadOfList;
}