255. Verify Preorder Sequence in Binary Search Tree

本文介绍两种方法来验证一个整数数组是否为有效的二叉搜索树的前序遍历序列。第一种方法采用分治策略,第二种方法使用常数空间复杂度,并通过栈来模拟遍历过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?


Solution 1 :  Divide and conquer

public class Solution {
    public boolean verifyPreorder(int[] preorder) {
        return verify(preorder,0,preorder.length - 1);
    }
    
    public boolean verify(int[] preorder, int start, int end){
        if(start >= end) return true;
        int p = preorder[start];
        int i = start + 1;
        while(i <= end){
            if(preorder[i] > p) break;
            i++;
        }
        int j = i;
        while(j <= end){
            if(preorder[j] < p) return false;
            j++;
        }
    
        return verify(preorder,start + 1, i - 1) && verify(preorder,i,end);
    }
}
Solution 2 : from https://discuss.leetcode.com/topic/21217/java-o-n-and-o-1-extra-space

Kinda simulate the traversal, keeping a stack of nodes (just their values) of which we're still in the left subtree. If the next number is smaller than the last stack value, then we're still in the left subtree of all stack nodes, so just push the new one onto the stack. But before that, pop all smaller ancestor values, as we must now be in their right subtrees (or even further, in the right subtree of an ancestor). Also, use the popped values as a lower bound, since being in their right subtree means we must never come across a smaller number anymore.

public boolean verifyPreorder(int[] preorder) {
    int low = Integer.MIN_VALUE;
    Stack<Integer> path = new Stack();
    for (int p : preorder) {
        if (p < low)
            return false;
        while (!path.empty() && p > path.peek())
            low = path.pop();
        path.push(p);
    }
    return true;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值