劍指 Offer 33. 二叉搜尋樹的後序遍歷序列

輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷結果。如果是則返回 true,否則返回 false。假設輸入的陣列的任意兩個數字都互不相同。

參考以下這顆二叉搜尋樹:

  1. 5
  2. / \
  3. 2 6
  4. / \
  5. 1 3

示例 1:

  1. 輸入: [1,6,3,2,5]
  2. 輸出: false

示例 2:

  1. 輸入: [1,3,2,6,5]
  2. 輸出: true

提示:

  • 陣列長度 <= 1000

解題思路:

解題之前,要先明晰一些基本概念。

  • 後序遍歷定義: [ 左子樹 | 右子樹 | 根節點 ] ,即遍歷順序為 “左、右、根” 。
  • 二叉搜尋樹定義: 左子樹中所有節點的值 << 根節點的值;右子樹中所有節點的值 >> 根節點的值;其左、右子樹也分別為二叉搜尋樹。

遞迴思路

個人當初做這道題的思路如下:

首先想到劃分左右子樹,然後再判斷是否為二叉搜尋樹。

在判斷左右子樹的時候,設定一個temp依次遍歷完整左子樹,然後等大於根節點的樹的時候直接break。

然後再建立rightTreeNode再遍歷右子樹,如果最後postorder[i]等於根節點的樹,遍歷結束。

最後在判斷rightTreeNode與end是否相同,且要用&&,必須使rightTreeNode == end、recur(postorder,start,temp)、recur(postorder,temp + 1,end - 1)都是true才能返回。

  1. class Solution {
  2. public boolean verifyPostorder(int[] postorder) {
  3. return recur(postorder,0,postorder.length - 1);
  4. }
  5. boolean recur(int[] postorder, int start, int end){
  6. if(start >= end) return true;
  7. int temp = start;
  8. // 找到右子樹結點第一次出現的地方。(或者說是遍歷完整棵左子樹)
  9. for(int i = start; i <= end; ++i){
  10. if(postorder[i] < postorder[end]){
  11. temp = i;
  12. }
  13. else break;
  14. }
  15. int rightTreeNode = temp + 1; // 後序遍歷右子樹時會訪問的第一個結點的下標。
  16. // 驗證右子樹所有結點是否都大於根結點。
  17. for(int i = rightTreeNode; i <= end; ++i){
  18. if(postorder[i] > postorder[end])
  19. ++rightTreeNode;
  20. }
  21. return rightTreeNode == end && recur(postorder,start,temp) && recur(postorder,temp + 1,end - 1);
  22. }
  23. }

這個是K神更為簡潔的程式碼的演算法思路:

  • 終止條件:當i>=j時候,說明此子樹的節點數量小於<=1,則直接返回true即可

  • 遞推工作:

    1. 劃分左右子樹: 遍歷後序遍歷的 [i, j][i,j] 區間元素,尋找 第一個大於根節點 的節點,索引記為 m。此時,可劃分出左子樹區間 [i,m-1][i,m−1] 、右子樹區間 [m, j - 1][m,j−1] 、根節點索引 jj 。

    2. 判斷是否為二叉搜尋樹:

      左子樹區間 [i, m - 1][i,m−1] 內的所有節點都應 << postorder[j]。而第 1.劃分左右子樹 步驟已經保證左子樹區間的正確性,因此只需要判斷右子樹區間即可。

      右子樹區間 [m, j-1][m,j−1] 內的所有節點都應 >> postorder[j]。實現方式為遍歷,當遇到 ≤postorder[j] 的節點則跳出;則可通過 p = j判斷是否為二叉搜尋樹。

  • 返回值: 所有子樹都需正確才可判定正確,因此使用 與邏輯符 &&&& 連線。

    p = j: 判斷 此樹 是否正確。

    recur(i, m - 1): 判斷 此樹的左子樹 是否正確。

    recur(m, j - 1): 判斷 此樹的右子樹 是否正確。

  1. class Solution {
  2. public boolean verifyPostorder(int[] postorder) {
  3. return recur(postorder, 0, postorder.length - 1);
  4. }
  5. boolean recur(int[] postorder, int i, int j) {
  6. if(i >= j) return true;
  7. int p = i;
  8. while(postorder[p] < postorder[j]) p++;
  9. int m = p;
  10. while(postorder[p] > postorder[j]) p++;
  11. return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);
  12. }
  13. }

參考連結:

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/