zoukankan      html  css  js  c++  java
  • 面试题27:二叉搜索树与双向链表

    这题逻辑比较难:

    把左子树中最大的节点,根节点,右子树中最小的节点链接起来;

    需要用pLastNodeInList来标记上一个节点

    注意这里pLastNodeInList用的是BinaryTreeNode**

     1 BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
     2 {
     3     BinaryTreeNode *pLastNodeInList = NULL;
     4     ConvertNode(pRootOfTree, &pLastNodeInList);
     5 
     6     // pLastNodeInList指向双向链表的尾结点,
     7     // 我们需要返回头结点
     8     BinaryTreeNode *pHeadOfList = pLastNodeInList;
     9     while(pHeadOfList != NULL && pHeadOfList->m_pLeft != NULL)
    10         pHeadOfList = pHeadOfList->m_pLeft;
    11 
    12     return pHeadOfList;
    13 }
    14 
    15 void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
    16 {
    17     if(pNode == NULL)
    18         return;
    19 
    20     BinaryTreeNode *pCurrent = pNode;
    21 
    22     if (pCurrent->m_pLeft != NULL)
    23         ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
    24 
    25     pCurrent->m_pLeft = *pLastNodeInList; 
    26     if(*pLastNodeInList != NULL)
    27         (*pLastNodeInList)->m_pRight = pCurrent;
    28 
    29     *pLastNodeInList = pCurrent;
    30 
    31     if (pCurrent->m_pRight != NULL)
    32         ConvertNode(pCurrent->m_pRight, pLastNodeInList);
    33 }
  • 相关阅读:
    缺少一个=出现的问题
    快速排序+归并排序
    ACwing简单题(14)
    浅谈#ifndef
    fstream 使用详解
    _stat函数的使用
    关于文件结构体的使用
    new的使用
    ACwing13题目
    ACwing13题
  • 原文地址:https://www.cnblogs.com/raichen/p/5652670.html
Copyright © 2011-2022 走看看