当前位置:   article > 正文

算法——二叉搜索树转换成双向链表c++实现_将二叉搜索树转换为双向排序链表c++

将二叉搜索树转换为双向排序链表c++

题目:将二叉搜索树换成双向链表

思路:利用树的中序遍历(左根右),再利用两个“快慢”指针,pLast比pCur慢一步,通过这两个指针建立双向链表

  1. BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
  2. {
  3. BinaryTreeNode *pLastNodeInList = nullptr;
  4. ConvertNode(pRootOfTree, &pLastNodeInList);
  5. // pLastNodeInList指向双向链表的尾结点,
  6. // 我们需要返回头结点
  7. BinaryTreeNode *pHeadOfList = pLastNodeInList;
  8. while(pHeadOfList != nullptr && pHeadOfList->m_pLeft != nullptr)
  9. pHeadOfList = pHeadOfList->m_pLeft;
  10. return pHeadOfList;
  11. }
  12. void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
  13. {
  14. if(pNode == nullptr)
  15. return;
  16. BinaryTreeNode *pCurrent = pNode;
  17. if (pCurrent->m_pLeft != nullptr)
  18. ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
  19. pCurrent->m_pLeft = *pLastNodeInList;
  20. if(*pLastNodeInList != nullptr)
  21. (*pLastNodeInList)->m_pRight = pCurrent;
  22. *pLastNodeInList = pCurrent;
  23. if (pCurrent->m_pRight != nullptr)
  24. ConvertNode(pCurrent->m_pRight, pLastNodeInList);
  25. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/404113
推荐阅读
相关标签
  

闽ICP备14008679号