程式員面試題精選100題(01)-把二元尋找樹轉變成排序的雙向鏈表

來源:互聯網
上載者:User

轉載地址:http://zhedahht.blog.163.com/blog/static/254111742007127104759245/

題目:輸入一棵二元尋找樹,將該二元尋找樹轉換成一個排序的雙向鏈表。要求不能建立任何新的結點,只調整指標的指向。

  比如將二元尋找樹
                                            10
                                          /    \
                                        6       14
                                      /  \     /  \
                                    4     8  12    16
轉換成雙向鏈表

4=6=8=10=12=14=16。

分析:本題是微軟的面試題。很多與樹相關的題目都是用遞迴的思路來解決,本題也不例外。下面我們用兩種不同的遞迴思路來分析。

  思路一:當我們到達某一結點準備調整以該結點為根結點的子樹時,先調整其左子樹將左子樹轉換成一個排好序的左子鏈表,再調整其右子樹轉換右子鏈表。最近連結左子鏈表的最右結點(左子樹的最大結點)、當前結點和右子鏈表的最左結點(右子樹的最小結點)。從樹的根結點開始遞迴調整所有結點。

  思路二:我們可以中序遍曆整棵樹。按照這個方式遍曆樹,比較小的結點先訪問。如果我們每訪問一個結點,假設之前訪問過的結點已經調整成一個排序雙向鏈表,我們再把調整當前結點的指標將其連結到鏈表的末尾。當所有結點都訪問過之後,整棵樹也就轉換成一個排序雙向鏈表了。

參考代碼:

首先我們定義二元尋找樹結點的資料結構如下:

struct BSTreeNode // a node in the binary search tree    {        int          m_nValue; // value of node        BSTreeNode  *m_pLeft;  // left child of node        BSTreeNode  *m_pRight; // right child of node    };

思路一對應的代碼:

///////////////////////////////////////////////////////////////////////// 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-tree      if(pNode->m_pLeft)            pLeft = ConvertNode(pNode->m_pLeft, false);      // Connect the greatest node in the left sub-tree to the current node      if(pLeft)      {            pLeft->m_pRight = pNode;            pNode->m_pLeft = pLeft;      }      // Convert the right sub-tree      if(pNode->m_pRight)            pRight = ConvertNode(pNode->m_pRight, true);      // Connect the least node in the right sub-tree to the current node      if(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 node      if(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 node      else      {            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 true      return ConvertNode(pHeadOfTree, true);}

思路二對應的代碼:

///////////////////////////////////////////////////////////////////////// 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-tree      if (pCurrent->m_pLeft != NULL)            ConvertNode(pCurrent->m_pLeft, pLastNodeInList);      // Put the current node into the double-linked list      pCurrent->m_pLeft = pLastNodeInList;       if(pLastNodeInList != NULL)            pLastNodeInList->m_pRight = pCurrent;      pLastNodeInList = pCurrent;      // Convert the right sub-tree      if (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 list      BSTreeNode *pHeadOfList = pLastNodeInList;      while(pHeadOfList && pHeadOfList->m_pLeft)            pHeadOfList = pHeadOfList->m_pLeft;      return pHeadOfList;}

非遞迴演算法如下,其中的棧的部分操作需要自己完成:

BiTree Link(BiTree T){BiTree p;int i=0;InitStack();while(T != NULL || !StackEmpty(S)){while(T != NULL){Push(S,T);T = T->lchild;}if(!StackEmpty(S)){T = Pop(S);if(i == 0){i++;p = T;p->lchild = NULL;printf("%c",T->value); }else{p->rchild = T;T->lchild = p;p = p->rchild;printf("%c",T->value);}T = T->rchild;}}printf("\n");p->rchild = NULL;return p;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.