find_if的带参数使用。递归。
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if (postorder.empty()) {
return true;
}
return verifyPostorder(postorder, 0, postorder.size() - 1);
}
private:
class firstMoreThan {
public:
firstMoreThan(const int root_) : root(root_) {}
bool operator()(const int i) {
return (i > root);
}
private:
const int root;
};
class firstLessThan {
public:
firstLessThan(const int root_) : root(root_) {}
bool operator()(const int i) {
return (i < root);
}
private:
const int root;
};
bool verifyPostorder(const vector<int>& postorder, int i, int j) {
if (j - i <= 1) {
return true;
}
int root = postorder[j];
auto it = find_if(postorder.begin() + i, postorder.begin() + j, firstMoreThan(root));
if (it >= postorder.begin() + j) {
return verifyPostorder(postorder, i, j - 1);
} else {
auto itTemp = find_if(it, postorder.begin() + j, firstLessThan(root));
if (itTemp != postorder.begin() + j) {
return false;
}
return verifyPostorder(postorder, i, it - postorder.begin() - 1) &&
verifyPostorder(postorder, it - postorder.begin(), j - 1);
}
}
};