题目描述:
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.
Consider the following binary search tree:
5
/ \
2 6
/ \
1 3
Example 1:
Input: [5,2,6,1,3]
Output: false
Example 2:
Input: [5,2,1,3,6]
Output: true
Follow up:
Could you do it using only constant space complexity?
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
stack<int> s; // s从栈底到栈顶维护一个递减序列,遍历左子树时一直累积,遍历右子树时从栈中寻找根节点
int low=INT_MIN; // 当遍历根节点的右子树时,low表示根节点的值,右子树所有节点值都要大于low
for(int x:preorder)
{
if(x<low) return false;
while(!s.empty()&&x>s.top()) // 当x<s.top()时,上一次的栈顶元素就是x的根节点
{
low=s.top();
s.pop();
}
s.push(x);
}
return true;
}
};
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
int i=-1; //必须是-1,因为i表示栈顶的下标,那么空栈的栈顶下标就是-1
int low=INT_MIN; // 当遍历根节点的右子树时,low表示根节点的值,右子树所有节点值都要大于low
for(int x:preorder)
{
if(x<low) return false;
while(i>=0&&x>preorder[i]) // 用数组模拟栈,如果x大于栈顶元素,i向左移动
{
low=preorder[i];
i--;
}
i++;
preorder[i]=x;
}
return true;
}
};
本文探讨了如何验证一个整数序列是否为二叉搜索树的正确前序遍历序列。通过使用栈来维护递减序列,并在遍历过程中检查节点值的有效性,实现了常数空间复杂度的解决方案。

被折叠的 条评论
为什么被折叠?



