255. Verify Preorder Sequence in Binary Search Tree
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
int low = INT_MIN;
stack<int> nodes;
for(auto p : preorder){
if(p < low) return false;
while(!nodes.empty() && p > nodes.top()){
// find the new lower bound
low = nodes.top(); nodes.pop();
}
// new reference
nodes.push(p);
}
return true;
}
};Last updated
Was this helpful?