赞
踩
题目:将二叉搜索树换成双向链表
思路:利用树的中序遍历(左根右),再利用两个“快慢”指针,pLast比pCur慢一步,通过这两个指针建立双向链表
- BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
- {
- BinaryTreeNode *pLastNodeInList = nullptr;
- ConvertNode(pRootOfTree, &pLastNodeInList);
-
- // pLastNodeInList指向双向链表的尾结点,
- // 我们需要返回头结点
- BinaryTreeNode *pHeadOfList = pLastNodeInList;
- while(pHeadOfList != nullptr && pHeadOfList->m_pLeft != nullptr)
- pHeadOfList = pHeadOfList->m_pLeft;
-
- return pHeadOfList;
- }
-
- void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
- {
- if(pNode == nullptr)
- return;
-
- BinaryTreeNode *pCurrent = pNode;
-
- if (pCurrent->m_pLeft != nullptr)
- ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
-
- pCurrent->m_pLeft = *pLastNodeInList;
- if(*pLastNodeInList != nullptr)
- (*pLastNodeInList)->m_pRight = pCurrent;
-
- *pLastNodeInList = pCurrent;
- if (pCurrent->m_pRight != nullptr)
- ConvertNode(pCurrent->m_pRight, pLastNodeInList);
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。