LeetCode刷题实战255:验证前序遍历序列二叉搜索树
共 2616字,需浏览 6分钟
·
2021-05-05 06:58
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up: Could you do it using only constant space complexity?
示例
示例 1:
输入: [5,2,6,1,3]
输出: false
示例 2:
输入: [5,2,1,3,6]
输出: true
进阶挑战:
您能否使用恒定的空间复杂度来完成此题?
解题
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
if (!preorder.size()) return true;
stack<int> s;
s.push(preorder[0]);
int temp = -1e10;
for (int i=1;i<preorder.size();i++)
{
if (preorder[i] < temp) return false;
while(!s.empty() && preorder[i] > s.top())
{
temp=s.top();
s.pop();
}
s.push(preorder[i]);
}
return true;
}
};