LeetCode #255 - Verify Preorder Sequence in Binary Search Tree

本文探讨了如何验证一个整数序列是否为二叉搜索树的正确前序遍历序列。通过使用栈来维护递减序列,并在遍历过程中检查节点值的有效性,实现了常数空间复杂度的解决方案。

题目描述:

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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值