日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

程序员面试题精选100题(11)-求二元查找树的镜像[数据结构]

發布時間:2025/3/21 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 程序员面试题精选100题(11)-求二元查找树的镜像[数据结构] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:輸入一顆二元查找樹,將該樹轉換為它的鏡像,即在轉換后的二元查找樹中,左子樹的結點都大于右子樹的結點。用遞歸和循環兩種方法完成樹的鏡像轉換。

例如輸入:

???? 8
??? /? \
? 6????? 10
?/\?????? /\
5? 7??? 9?? 11

輸出:

????? 8
??? /? \
? 10 ???6
?/\??? ??/\
11??9? 7? 5

定義二元查找樹的結點為:

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


分析:盡管我們可能一下子不能理解鏡像是什么意思,但上面的例子給我們的直觀感覺,就是交換結點的左右子樹。我們試著在遍歷例子中的二元查找樹的同時來交換每個結點的左右子樹。遍歷時首先訪問頭結點8,我們交換它的左右子樹得到:

??????8
??? /? \
? 10?? ?6
?/\??? ? /\
9??11? 5? 7

我們發現兩個結點6和10的左右子樹仍然是左結點的值小于右結點的值,我們再試著交換他們的左右子樹,得到:

????? 8
??? /? \
? 10 ???6
?/\??? ??/\
11??9? 7?? 5

剛好就是要求的輸出。

上面的分析印證了我們的直覺:在遍歷二元查找樹時每訪問到一個結點,交換它的左右子樹。這種思路用遞歸不難實現,將遍歷二元查找樹的代碼稍作修改就可以了。參考代碼如下:

/// // Mirror a BST (swap the left right child of each node) recursively // the head of BST in initial call /// void MirrorRecursively(BSTreeNode *pNode) {if(!pNode)return;// swap the right and left child sub-treeBSTreeNode *pTemp = pNode->m_pLeft;pNode->m_pLeft = pNode->m_pRight;pNode->m_pRight = pTemp;// mirror left child sub-tree if not nullif(pNode->m_pLeft)MirrorRecursively(pNode->m_pLeft); // mirror right child sub-tree if not nullif(pNode->m_pRight)MirrorRecursively(pNode->m_pRight); }

由于遞歸的本質是編譯器生成了一個函數調用的棧,因此用循環來完成同樣任務時最簡單的辦法就是用一個輔助棧來模擬遞歸。首先我們把樹的頭結點放入棧中。在循環中,只要棧不為空,彈出棧的棧頂結點,交換它的左右子樹。如果它有左子樹,把它的左子樹壓入棧中;如果它有右子樹,把它的右子樹壓入棧中。這樣在下次循環中就能交換它兒子結點的左右子樹了。參考代碼如下:

/// // Mirror a BST (swap the left right child of each node) Iteratively // Input: pTreeHead: the head of BST /// void MirrorIteratively(BSTreeNode *pTreeHead) {if(!pTreeHead)return;std::stack<BSTreeNode *> stackTreeNode;stackTreeNode.push(pTreeHead);while(stackTreeNode.size()){BSTreeNode *pNode = stackTreeNode.top();stackTreeNode.pop();// swap the right and left child sub-treeBSTreeNode *pTemp = pNode->m_pLeft;pNode->m_pLeft = pNode->m_pRight;pNode->m_pRight = pTemp;// push left child sub-tree into stack if not nullif(pNode->m_pLeft)stackTreeNode.push(pNode->m_pLeft);// push right child sub-tree into stack if not nullif(pNode->m_pRight)stackTreeNode.push(pNode->m_pRight);} }

本文已經收錄到《劍指Offer——名企面試官精講典型編程題》一書中,有改動,書中的分析講解更加詳細。歡迎關注。

博主何海濤對本博客文章享有版權。網絡轉載請注明出處http://zhedahht.blog.163.com/。整理出版物請和作者聯系。


總結

以上是生活随笔為你收集整理的程序员面试题精选100题(11)-求二元查找树的镜像[数据结构]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。