程序员面试题精选100题(06)-二元查找树的后序遍历结果[数据结构]
例如輸入5、7、6、9、11、10、8,由于這一整數序列是如下樹的后序遍歷結果:
??? ?????8
?????? /? \
????? 6??? 10
??? / \????/ \
?? 5?? 7???9??11
因此返回true。
如果輸入7、4、6、5,沒有哪棵樹的后序遍歷的結果是這個序列,因此返回false。
分析:這是一道trilogy的筆試題,主要考查對二元查找樹的理解。
在后續遍歷得到的序列中,最后一個元素為樹的根結點。從頭開始掃描這個序列,比根結點小的元素都應該位于序列的左半部分;從第一個大于跟結點開始到跟結點前面的一個元素為止,所有元素都應該大于跟結點,因為這部分元素對應的是樹的右子樹。根據這樣的劃分,把序列劃分為左右兩部分,我們遞歸地確認序列的左、右兩部分是不是都是二元查找樹。
參考代碼:
using namespace std;/// // Verify whether a squence of integers are the post order traversal // of a binary search tree (BST) // Input: squence - the squence of integers // length - the length of squence // Return: return ture if the squence is traversal result of a BST, // otherwise, return false /// bool verifySquenceOfBST(int squence[], int length) {if(squence == NULL || length <= 0)return false;// root of a BST is at the end of post order traversal squenceint root = squence[length - 1];// the nodes in left sub-tree are less than the rootint i = 0;for(; i < length - 1; ++ i){if(squence[i] > root)break;}// the nodes in the right sub-tree are greater than the rootint j = i;for(; j < length - 1; ++ j){if(squence[j] < root)return false;}// verify whether the left sub-tree is a BSTbool left = true;if(i > 0)left = verifySquenceOfBST(squence, i);// verify whether the right sub-tree is a BSTbool right = true;if(i < length - 1)right = verifySquenceOfBST(squence + i, length - i - 1);return (left && right); }
本文已經收錄到《劍指Offer——名企面試官精講典型編程題》一書中,有改動,書中的分析講解更加詳細。歡迎關注。這篇博客對應的英文版詳見http://codercareer.blogspot.com/2011/09/no-06-post-order-traversal-sequences-of.html。歡迎感興趣的朋友閱讀并批評指正。
本題已被九度Online Judge系統收錄,歡迎讀者移步到http://ac.jobdu.com/hhtproblems.php在線測試自己的代碼。
?? ? ?博主何海濤對本博客文章享有版權。網絡轉載請注明出處
總結
以上是生活随笔為你收集整理的程序员面试题精选100题(06)-二元查找树的后序遍历结果[数据结构]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员面试题精选100题(05)-查找最
- 下一篇: 程序员面试题精选100题(07)-翻转句