1. 程式人生 > 其它 >springboot簡單專案(5) 員工資訊管理

springboot簡單專案(5) 員工資訊管理

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

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

    5
    / \
   2   6
  / \
 1   3

  

示例 1:

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

示例 2:

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

程式碼和思路:

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        //首先明確一點,二叉搜尋樹是有序樹
        if (postorder.length < 2){
            return true;
        }
        return verify(postorder, 0, postorder.length - 1);
    }
    // 遞迴實現
    private boolean verify(int[] postorder, int left, int right)
    {
        if (left >= right) 
        {
            return true; //當前區域不合法的時候直接返回true就好
        }
        int rootValue = postorder[right]; // 當前樹的根節點的值
        int k = left;
        while (k < right && postorder[k] < rootValue)
        {
            // 從當前區域找到第一個大於跟節點的,說明後續區域樹值都在右子樹中
            k++;
        }
        for (int i = k; i < right; i++)
        {
            // 進行判斷後續的區域是否所有的值都是大於當前的根節點,如果出現小於的值直接返回false
            if(postorder[i] < rootValue)
            {
                return false;
            }
        }
        // 當前樹沒問題就檢查左右子樹
        if (!verify(postorder, left, k-1))
        {
            return false; // 檢查左子樹
        }
        if (!verify(postorder, k, right - 1))
        {
            return false;  //檢查右子樹
        }
        return true; //最終都沒問題就返回 true
    }
}