程序员面试题精选100题(11)-求二元查找树的镜像[数据结构]
例如輸入:
???? 8
??? /? \
? 6????? 10
?/\?????? /\
5? 7??? 9?? 11
輸出:
????? 8
??? /? \
? 10 ???6
?/\??? ??/\
11??9? 7? 5
定義二元查找樹(shù)的結(jié)點(diǎn)為:
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 };
分析:盡管我們可能一下子不能理解鏡像是什么意思,但上面的例子給我們的直觀感覺(jué),就是交換結(jié)點(diǎn)的左右子樹(shù)。我們?cè)囍诒闅v例子中的二元查找樹(shù)的同時(shí)來(lái)交換每個(gè)結(jié)點(diǎn)的左右子樹(shù)。遍歷時(shí)首先訪問(wèn)頭結(jié)點(diǎn)8,我們交換它的左右子樹(shù)得到:
??????8
??? /? \
? 10?? ?6
?/\??? ? /\
9??11? 5? 7
我們發(fā)現(xiàn)兩個(gè)結(jié)點(diǎn)6和10的左右子樹(shù)仍然是左結(jié)點(diǎn)的值小于右結(jié)點(diǎn)的值,我們?cè)僭囍粨Q他們的左右子樹(shù),得到:
????? 8
??? /? \
? 10 ???6
?/\??? ??/\
11??9? 7?? 5
剛好就是要求的輸出。
上面的分析印證了我們的直覺(jué):在遍歷二元查找樹(shù)時(shí)每訪問(wèn)到一個(gè)結(jié)點(diǎn),交換它的左右子樹(shù)。這種思路用遞歸不難實(shí)現(xiàn),將遍歷二元查找樹(shù)的代碼稍作修改就可以了。參考代碼如下:
/// // 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); }由于遞歸的本質(zhì)是編譯器生成了一個(gè)函數(shù)調(diào)用的棧,因此用循環(huán)來(lái)完成同樣任務(wù)時(shí)最簡(jiǎn)單的辦法就是用一個(gè)輔助棧來(lái)模擬遞歸。首先我們把樹(shù)的頭結(jié)點(diǎn)放入棧中。在循環(huán)中,只要棧不為空,彈出棧的棧頂結(jié)點(diǎn),交換它的左右子樹(shù)。如果它有左子樹(shù),把它的左子樹(shù)壓入棧中;如果它有右子樹(shù),把它的右子樹(shù)壓入棧中。這樣在下次循環(huán)中就能交換它兒子結(jié)點(diǎn)的左右子樹(shù)了。參考代碼如下:
/// // 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);} }本文已經(jīng)收錄到《劍指Offer——名企面試官精講典型編程題》一書(shū)中,有改動(dòng),書(shū)中的分析講解更加詳細(xì)。歡迎關(guān)注。
博主何海濤對(duì)本博客文章享有版權(quán)。網(wǎng)絡(luò)轉(zhuǎn)載請(qǐng)注明出處http://zhedahht.blog.163.com/。整理出版物請(qǐng)和作者聯(lián)系。
總結(jié)
以上是生活随笔為你收集整理的程序员面试题精选100题(11)-求二元查找树的镜像[数据结构]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 程序员面试题精选100题(10)-排序数
- 下一篇: 程序员面试题精选100题(12)-从上往