2023-9-29 JZ33 二叉搜索树的后序遍历序列

题目链接:二叉搜索树的后序遍历序列

2023-9-29 JZ33 二叉搜索树的后序遍历序列_第1张图片

import java.util.*;
public class Solution {
    int [] seq;
    public boolean VerifySquenceOfBST(int [] sequence) {
        if(sequence.length <= 0) return false;
        this.seq = sequence;
        return dfs(0, seq.length - 1);
    }

    public boolean dfs(int l, int r){
        if(l >= r) return true;
        int root = seq[r];
        int k = l;
        while(k < r && seq[k] < seq[r]) k ++;
        for(int i = k; i < r; i ++)
            if(seq[i] < root)
                return false;
        return dfs(l, k - 1) && dfs(k, r - 1);
    }
}

你可能感兴趣的:(深度优先,算法,剑指offer)