LCOF劍指offer--面試題33. 二叉搜索樹的後序遍歷序列

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

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

     5
    / \
   2   6
  / \
 1   3

示例 1:

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

示例 2:

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

提示:

數組長度 <= 1000

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
遞歸
解答:

class Solution {
public:
    bool verifyPostorder(vector<int>& postorder) {
        if(postorder.size()<2) return true;

        return helper(postorder,0 , postorder.size()-1);
    }

    bool helper(vector<int>& postorder,int begin, int end){
        if(begin>=end) return true;//考慮了左右子樹爲空的時候

        int i = begin;
        while(postorder[i]<postorder[end]){
            i++;
        }

        int boundary = i;

        for(;i<end;i++){
            if(postorder[i]<postorder[end]) return false;
        }

        return helper(postorder, begin, boundary-1)&&helper(postorder,boundary,end-1);


    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章